环境 jdk1.8
1.把Map转换为List
1 Map<String,String> map = new HashMap<>(); 2 3 List keyList = new ArrayList(map.keySet()); 4 List valueList = new ArrayList(map.values()); 5 List entryList = new ArrayList(map.entrySet());
2.遍历map
1 for (Map.Entry<String,String> entry : map.entrySet()) { 2 String key = entry.getKey(); 3 String value = entry.getValue(); 4 }
1 //jdk1.8的特性 2 map.forEach((key,value) -> System.out.println(key+" "+value));
3.依据map的key对map排序
1 List<Map.Entry<String,String>> list = new ArrayList(map.entrySet()); 2 Collections.sort(list,(e1,e2) -> e1.getKey().compareTo(e2.getKey()));
1 SortedMap<String, String> sortedMap = new TreeMap<>((key1,key2) -> key1.compareTo(key2)); 2 sortedMap.putAll(map);
4.依据map的value值对map排序
1 List<Map.Entry<String,String>> list = new ArrayList(map.entrySet()); 2 Collections.sort(list,(e1,e2) -> e1.getValue().compareTo(e2.getValue()));
5.初始化一个不可变的map
public class Test { private static final Map map; static { map = new HashMap(); map.put(1, "one"); map.put(2, "two"); } //这样初始化后,还是可以继续向map里面添加元素的 } //可以这样做 public class Test { private static final Map map; static { Map aMap = new HashMap(); aMap.put(1, "one"); aMap.put(2, "two"); map = Collections.unmodifiableMap(aMap); } }
6.HashMap,HashTable,TreeMap 之间的比较
- 有序性:HashMap,HashTable放进去的元素是无序的。TreeMap可以按照key的自然序排序或者是一个比较器(Comparator)排序
- key-value的限制:HashMap允许null key,null value,HashTable不允许null key,null value,如果TreeMap按照key的自然序排序的话,它也是不允许null key
- 同步性:只有HashTable是线程同步的(synchronized)
如下表:
| HashMap | Hashtable | TreeMap | |
| iteration order | no | no | yes |
| null key-value | yes-yes | no-no | no-yes |
| synchronized | no | yes | no |
| time performance | O(1) | O(1) | O(log n) |
| implementation | buckets | buckets | red-black tree |
7.双向map
jdk不支持双向map(bidirectional map),但是 Apache Common Collections and Guava均提供了双向map,分别为:BidiMap 和 BiMap
8.创建一个空map
1 map = Collections.emptyMap();
浙公网安备 33010602011771号