编写一个多条件过滤功能时,想使用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

posted on 2019-05-05 15:12  miaoying  阅读(2547)  评论(0编辑  收藏  举报