Java中遍历ConcurrentHashMap的四种方式分别是什么

本篇文章给大家分享的是有关Java中遍历ConcurrentHashMap的四种方式分别是什么,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

方式一:在for-each循环中使用entries来遍历

System.out.println("方式一:在for-each循环中使用entries来遍历");

for (Map.Entry<String, String> entry: map.entrySet()) {

System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

 }

方法二:在for-each循环中遍历keys或values,这种方式适用于需要值或者键的情况,方法二比方法一快了10%

System.out.println("方法二:在for-each循环中遍历keys或values,这种方式适用于需要值或者键的情况");//遍历键for (String key : map.keySet()) {System.out.println("key = " + key);}//遍历值for (String value : map.values()) {System.out.println("value = " + value);}

方法三:使用Iterator遍历,使用并发集合不会报异常,性能类似于方法二

//使用泛型Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();System.out.println("使用Iterator遍历,并且使用泛型:");

while (entries.hasNext()) {Map.Entry<String, String> entry = entries.next();

System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());//注意这里操作了集合,下面的的遍历不会再打印0

if("0".equals(entry.getKey())) {map.remove(entry.getKey());

 }

}

//不使用泛型

Iterator entrys = map.entrySet().iterator();

System.out.println("使用Iterator遍历,并且不使用泛型");

while (entrys.hasNext()) {Map.Entry entry = (Map.Entry) entrys.next();

String key = (String)entry.getKey();

String value = (String)entry.getValue();

System.out.println("Key = " + key + ", Value = " + value);

}

方式四:通过键找值遍历,该方法效率相当低,不建议使用

System.out.println("方式四:通过键找值遍历");

for (String key : map.keySet()) {String value = map.get(key);

System.out.println("Key = " + key + ", Value = " + value);

 }

}

以上就是Java中遍历ConcurrentHashMap的四种方式分别是什么,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注蜗牛博客行业资讯频道。

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接