A, traverse

1. Iterate through the list collection

List list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");

list.forEach(lists -> System.out.println(lists)); / / output a, b, c
// output only b
list.forEach(e ->{
    if("b".equals(e)){ System.out.println(e); }});Copy the code

2. Traverse the Map collection

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));
Copy the code

List<Map<String, Object>>

// Outputs the Map data in the List collection
result.forEach(map->
            map.forEach((key,value)->
                    System.out.println(key + "" + value)));
Copy the code

Java8 merge List<Map<String,Object>> into a 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);
Copy the code

Code:

Map<String, Object> haNew = new HashMap<>();
lists.forEach(haNew::putAll);
Copy the code

or

Map<String, Object> result = lists
            .stream()
            .map(Map::entrySet)
            .flatMap(Collection::stream)
            .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
Copy the code

The code above will report an error if there are duplicate keys

// Do not want to overwrite, keep the original value:
lists.stream().flatMap(m -> m.entrySet().stream())
              .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a));
              
// Overwrite key with the same value,
lists.stream().flatMap(m -> m.entrySet().stream())
              .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b)); 
Copy the code

reference

Use Java8 to merge List

> into a Map.