获取密钥
//Get Keys of childHashMap
Set<String> keys = parent.keySet().stream().
flatMap(child -> child.keySet().stream()).
collect(Collectors.toSet());
1.Stream on keySet of parent hashMap(迭代子 hashmap)
2.返回子hashmap的keySet(类似于{1},{2,3},{4,5})
child -> child.keySet().stream()
3.Flat上一步设置(就像将{1},{2,3},{4,5}转换为{1,2,3,4,5})
flatMap(child -> child.keySet().stream()).
4.返回键
collect(Collectors.toSet());
获取值
//Get Values of childHashMap
Collection<String> values = parent.keySet().stream()
.map(HashMap::values)
.flatMap(Collection::stream)
.collect(Collectors.toList());
1.Stream keySet 的父 hashMap(迭代子 hashmap)
2.子hashMap的返回值(如:{1},{2},{3})
3.使用flatMap将上一步变平(将{1},{2},{3}转换为{1,2,3})
flatMap(Collection::stream)
4.将值收集到列表中
collect(Collectors.toList())
示例
//Parent
HashMap<HashMap<String, String>, String> parent = new HashMap<>();
//Child HashMap 1
HashMap<String, String> childHashMap = new HashMap<>();
childHashMap.put("a", "b");
//Child HashMap2
HashMap<String, String> childHashMap2 = new HashMap<>();
childHashMap2.put("d", "e");
//Parent init
parent.put(childHashMap, "c");
parent.put(childHashMap2, "f");
//Get Keys
Set<String> keys = parent.keySet().stream().flatMap(child -> child.keySet().stream()).collect(Collectors.toSet());
//Get values
Collection<String> values = parent.keySet().stream().map(HashMap::values).flatMap(Collection::stream).collect(Collectors.toList());
//Print key and values
keys.forEach(System.out::println);
values.forEach(System.out::println);
结果 =
键 = a ,d
值 = e , b