Java中遍历ConcurrentHashMap的四种方式详解

这篇文章主要介绍了Java中遍历ConcurrentHashMap的四种方式详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

创新互联公司专注于企业成都营销网站建设、网站重做改版、灵山网站定制设计、自适应品牌网站建设、H5技术商城网站制作、集团公司官网建设、成都外贸网站建设公司、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为灵山等各大城市提供网站开发制作服务。

方式一:在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的四种方式详解
URL地址:https://www.cdcxhl.com/article20/pppdco.html

成都网站建设公司_创新互联,为您提供动态网站电子商务品牌网站建设Google标签优化网站排名

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

外贸网站制作