編寫一個多條件過濾功能時,想使用map作為過濾條件的容器,由於存在同一健匹配多個值的情況,所以就發現了jdk8的新的map:IdentityHashMap。使用它完美解決了我的問題。
對比IdentityHashMap與HashTable、HashMap,代碼如下:

IdentityHashMap 根據 key 進行排序:
public static void main(String[] args) { Map<String, String> map = new IdentityHashMap<>(); map.put("A1", "1"); map.put("A2", "3"); map.put(new String("A1"), "2"); map.put("A", "0"); List<Map.Entry> mappingList = new ArrayList(map.entrySet()); mappingList = mappingList.stream().sorted(Comparator.comparing((Map.Entry entry) -> entry.getKey().toString())).collect(Collectors.toList()); for (Map.Entry entry : mappingList) { System.out.println(entry.getKey() + ", " + entry.getValue()); } }
測試結果如下:
A, 0 A1, 2 A1, 1 A2, 3
這篇文章對IdentityHashMap分析的很棒,牆裂推薦!
https://www.jianshu.com/p/1b441546078a
