一、遍历
1. 遍历 list 集合
List list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.forEach(lists -> System.out.println(lists)); //输出 a,b,c
//只输出 b
list.forEach(e ->{
if("b".equals(e)){
System.out.println(e);
}
});
2. 遍历 map 集合
Map <String ,Integerr> map = new HashMap<>();
map.put("a",1);
map.put("b",2);
map.out("c",3);
map.forEach((k, v) -> System.out.println(k + v));
3. 遍历 List<Map<String, Object>>
//输出List集合中Map数据
result.forEach(map->
map.forEach((key,value)->
System.out.println(key + " " + value)));
二、使用 Java8 合并 List<Map<String,Object>> 为一个 Map?
Map<String,Object> h1 = new HashMap<>();
h1.put("12","fdsa");
Map<String,Object> h2 = new HashMap<>();
h2.put("h12","fdsa");
Map<String,Object> h3 = new HashMap<>();
h3.put("h312","fdsa");
List<Map<String,Object>> lists = new ArrayList<>();
lists.add(h1);
lists.add(h2);
lists.add(h3);
代码:
Map<String, Object> haNew = new HashMap<>();
lists.forEach(haNew::putAll);
或
Map<String, Object> result = lists
.stream()
.map(Map::entrySet)
.flatMap(Collection::stream)
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
如果有重复的key,上面的代码会报错
// 不想覆盖,保留最初的值:
lists.stream().flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a));
// 覆盖key相同的值,
lists.stream().flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b));
参考
Java8新特性之forEach+Lambda 表达式遍历Map和List
使用Java8 合并List<Map<String,Object>>为一个Map?