作者:多米音乐_35547384 | 来源:互联网 | 2021-09-27 09:17
Java 8 , Lambda + foreach 语法糖, 写起来非常的 clean
public static void main(String[] args) {
// map init
Map map = new HashMap<>();
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)
看代码吧~
public static void main(String[] args) {
// Map map = new HashMap();
Map map = new LinkedHashMap();
map.put("username","zhaokuo");
map.put("password", "123456");
map.put("email", "zhaokuo719@163.com");
map.put("sex", "男");
//第一种 用for循环的方式
for (Map.Entry m :map.entrySet()) {
System.out.println(m.getKey()+"\t"+m.getValue());
}
//利用迭代 (Iterator)
Set set=map.entrySet();
Iterator iterator=set.iterator();
while(iterator.hasNext()){
Map.Entry enter=(Entry) iterator.next();
System.out.println(enter.getKey()+"\t"+enter.getValue());
}
//利用KeySet 迭代
Iterator it = map.keySet().iterator();
while(it.hasNext()){
String key;
String value;
key=it.next().toString();
value=(String) map.get(key);
System.out.println(key+"--"+value);
}
//利用EnterySet迭代
Iterator i=map.entrySet().iterator();
System.out.println( map.entrySet().size());
String key;
String value;
while(i.hasNext()){
Map.Entry entry = (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
public static String getKeyByValue(Map map, Object value) {
String keys="";
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Entry) it.next();
Object obj = entry.getValue();
if (obj != null && obj.equals(value)) {
keys=(String) entry.getKey();
}
}
return keys;
}
以上这篇Java map 优雅的元素遍历方式说明就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。