JAVA8独有的map遍历方式(非常好用)
使用JAV8带来的map遍历方式使遍历非常简单
publicclassLambdaMap{
privateMapmap=newHashMap<>();
@Before
publicvoidinitData(){
map.put("key1","value1");
map.put("key2","value2");
map.put("key3","value3");
map.put("key4",4);
map.put("key5",5);
map.put("key5",'h');
}
/**
*遍历Map的方式一
*通过Map.keySet遍历key和value
*/
@Test
publicvoidtestErgodicWayOne(){
System.out.println("---------------------BeforeJAVA8------------------------------");
for(Stringkey:map.keySet()){
System.out.println("map.get("+key+")="+map.get(key));
}
System.out.println("---------------------JAVA8------------------------------");
map.keySet().forEach(key->System.out.println("map.get("+key+")="+map.get(key)));
}
/**
*遍历Map第二种
*通过Map.entrySet使用Iterator遍历key和value
*/
@Test
publicvoidtestErgodicWayTwo(){
System.out.println("---------------------BeforeJAVA8------------------------------");
Iterator>iterator=map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entryentry=iterator.next();
System.out.println("key:value="+entry.getKey()+":"+entry.getValue());
}
System.out.println("---------------------JAVA8------------------------------");
map.entrySet().iterator().forEachRemaining(item->System.out.println("key:value="+item.getKey()+":"+item.getValue()));
}
/**
*遍历Map第三种
*通过Map.entrySet遍历key和value,在大容量时推荐使用
*/
@Test
publicvoidtestErgodicWayThree(){
System.out.println("---------------------BeforeJAVA8------------------------------");
for(Map.Entryentry:map.entrySet()){
System.out.println("key:value="+entry.getKey()+":"+entry.getValue());
}
System.out.println("---------------------JAVA8------------------------------");
map.entrySet().forEach(entry->System.out.println("key:value="+entry.getKey()+":"+entry.getValue()));
}
/**
*遍历Map第四种
*通过Map.values()遍历所有的value,但不能遍历key
*/
@Test
publicvoidtestErgodicWayFour(){
System.out.println("---------------------BeforeJAVA8------------------------------");
for(Objectvalue:map.values()){
System.out.println("map.value="+value);
}
System.out.println("---------------------JAVA8------------------------------");
map.values().forEach(System.out::println);//等价于map.values().forEach(value->System.out.println(value));
}
/**
*遍历Map第五种
*通过k,v遍历,Java8独有的
*/
@Test
publicvoidtestErgodicWayFive(){
System.out.println("---------------------OnlyJAVA8------------------------------");
map.forEach((k,v)->System.out.println("key:value="+k+":"+v));
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。