Java 8 , Lambda + foreach 语法糖, 写起来非常的 clean
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public static void main(String[] args) {
// map init
Map<String, String> 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)
看代码吧~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
public static void main(String[] args) {
// Map<String, Object> map = new HashMap<String, Object>();
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put( "username" , "zhaokuo" );
map.put( "password" , "123456" );
map.put( "email" , "zhaokuo719@163.com" );
map.put( "sex" , "男" );
//第一种 用for循环的方式
for (Map.Entry<String, Object> 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<String, Object> enter=(Entry<String, Object>) 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" ));
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
//根据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 优雅的元素遍历方式说明就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/huangdingsheng/article/details/107110334