前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java8中遍历Map的常用四种方式

Java8中遍历Map的常用四种方式

作者头像
攻城狮的那点事
发布2019-12-24 15:56:21
10.1K0
发布2019-12-24 15:56:21
举报
文章被收录于专栏:攻城狮的那点事

如果你现在正在使用Java8,那一定要看看在Java8中,对map操作遍历可以采用第4种方式哦。

一,通过forEach循环遍历

代码语言:javascript
复制
public void test1() throws Exception {      
Map<Integer, String> map = new HashMap<>();      
map.put(1, "a");      
map.put(3, "c");      
map.put(4, "d");      
map.put(2, "b");      
for (Map.Entry<Integer, String> entry : map.entrySet()) {        
System.out.println("Key = " + entry.getKey() + " Value = "+ entry.getValue());      
}  
}

输出结果:

代码语言:javascript
复制
Key = 1 Value = aKey = 2 Value = bKey = 3 Value = cKey = 4 Value = d

二:通过forEach迭代键值对

如果你只想使用键或者值,推荐使用此方式

代码语言:javascript
复制
@Test
public void test2() throws Exception {    
Map<Integer, String> map = new HashMap<>();    
map.put(1, "a");    
map.put(3, "c");    
map.put(4, "d");    
map.put(2, "b");    
for (Integer key : map.keySet()) {        
System.out.println("Key = " + key);    
}    
for (String value : map.values()) {        
System.out.println("Value = " + value);    
}
}

输出结果:

代码语言:javascript
复制
Key = 1Key = 2 Key = 3 Key = 4Value = aValue = bValue = cValue = d

三:使用迭代器进行遍历

代码语言:javascript
复制
@Test
public void test3() throws Exception {    
Map<Integer, String> map = new HashMap<>();    
map.put(1, "a");    
map.put(3, "c");    
map.put(4, "d");    
map.put(2, "b");    
Iterator<Entry<Integer, String>> iterator = map.entrySet().iterator();    
while (iterator.hasNext()) {        
Map.Entry<Integer, String> entry = (Map.Entry<Integer, String>)iterator.next();        
Integer key = entry.getKey();        
String value = entry.getValue();        
System.out.println("Key = " + key + " Value = "+ value);      
}
}

输出结果:

代码语言:javascript
复制
Key = 1 Value = aKey = 2  Value = bKey = 3  Value = cKey = 4  Value = d

四:强烈推荐通过Java8 Lambda表达式遍历

代码语言:javascript
复制
@Test
public void test4() throws Exception {    
Map<Integer, String> map = new HashMap<>();    
map.put(1, "a");    
map.put(3, "c");    
map.put(4, "d");    
map.put(2, "b");    
map.forEach((key, value) -> {        
System.out.println("Key = " + key + "  " + " Value = " + value);    
});
}

输出结果:

代码语言:javascript
复制
Key = 1 Value = aKey = 2  Value = bKey = 3  Value = cKey = 4  Value = d
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-12-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 攻城狮的那点事 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档