Java map 优雅的元素遍历方式说明
Java8,Lambda+foreach语法糖,写起来非常的clean
publicstaticvoidmain(String[]args){
//mapinit
Mapmap=newHashMap<>();
map.put("k","v");
/*=====处理函数只有单条语句=====*/
map.forEach((k,v)->System.out.println(k+v));
/*=====处理函数有多个步骤=======*/
map.forEach((k,v)->{
System.out.println(111);
System.out.println(k+v);
});
}
补充知识:java遍历Map和根据Map的值(value)取键(key)
看代码吧~
publicstaticvoidmain(String[]args){
// Mapmap=newHashMap();
Mapmap=newLinkedHashMap();
map.put("username","zhaokuo");
map.put("password","123456");
map.put("email","zhaokuo719@163.com");
map.put("sex","男");
//第一种用for循环的方式
for(Map.Entrym:map.entrySet()){
System.out.println(m.getKey()+"\t"+m.getValue());
}
//利用迭代(Iterator)
Setset=map.entrySet();
Iteratoriterator=set.iterator();
while(iterator.hasNext()){
Map.Entryenter=(Entry)iterator.next();
System.out.println(enter.getKey()+"\t"+enter.getValue());
}
//利用KeySet迭代
Iteratorit=map.keySet().iterator();
while(it.hasNext()){
Stringkey;
Stringvalue;
key=it.next().toString();
value=(String)map.get(key);
System.out.println(key+"--"+value);
}
//利用EnterySet迭代
Iteratori=map.entrySet().iterator();
System.out.println(map.entrySet().size());
Stringkey;
Stringvalue;
while(i.hasNext()){
Map.Entryentry=(Map.Entry)i.next();
key=entry.getKey().toString();
value=entry.getValue().toString();
System.out.println(key+"===="+value);
}
System.out.println(getKeyByValue(map,"zhaokuo"));
}
//根据Value取Key
publicstaticStringgetKeyByValue(Mapmap,Objectvalue){
Stringkeys="";
Iteratorit=map.entrySet().iterator();
while(it.hasNext()){
Map.Entryentry=(Entry)it.next();
Objectobj=entry.getValue();
if(obj!=null&&obj.equals(value)){
keys=(String)entry.getKey();
}
}
returnkeys;
}
以上这篇Javamap优雅的元素遍历方式说明就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。