jdk8可重复key的Map: IdentityHashMap


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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM