HashMap, LinkedMap, TreeMap -- J
2019-10-03 本文已影响0人
Leahlijuan
总结:TreeMap有顺序,HashMap无顺序,LinkedHashMap的顺序与插入顺序相同
HashMap
Map<String, String> map = new HashMap<>();
int value = map.get(key);
int value = map.getOrDefault(key, default);
map.put(key, value);
map.size();
map.containsKey(key);
map.containsValue(value);
// travarse
for(Map.Entry<keytype, valuetype> entry: map.entrySet() {
entry.getKey();
entry.getValue();
}
// get key set
map.keySet();
// get value set
map.values();
map.remove(key);
map.remove(key, value);
map.putAll(anotherMap);
LinkedMap
元素的排列顺序与插入顺序相同
Map<String, String> map = new LinkedHashMap<>();
map.put("a","b");
map.put("c","d");
map.put("e","f");
for (Map.Entry<String, String> entry: map.entrySet()) {
System.out.println(entry.getKey());
}
// a, c, e
TreeMap
map中的elememts是按照一定顺序排列的,可以通过自定义comparator来确定排列顺序。
Map<String, String> map = new TreeMap<>();
// initialize a TreeMap with comparator
Map<int[], Integer> map = new TreeMap<>(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[1] < o2[1]) {
return -1;
}
return 1;
}
});
int[] a1 = {1,2};
int[] a2 = {1,6};
int[] a3 = {1,3};
map.put(a1,1);
map.put(a2,2);
map.put(a3,3);
Set<int[]> set = map.keySet(); // [1,2], [1,3], [1,6]
System.out.println(((TreeMap<int[], Integer>) map).firstKey());
// can traver TreeMap the same with HashMap