问题
How I can merge List<Map<String,String>>
to Map<String,String>
using flatMap
?
Here's what I've tried:
final Map<String, String> result = response
.stream()
.collect(Collectors.toMap(
s -> (String) s.get("key"),
s -> (String) s.get("value")));
result
.entrySet()
.forEach(e -> System.out.println(e.getKey() + " -> " + e.getValue()));
This does not work.
回答1:
Assuming that there are no conflicting keys in the maps contained in your list, try following:
Map<String, String> maps = list.stream()
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
回答2:
If you're ok with overriding the keys, you can just merge the Map
s into a single map with collect
, even without flatMap
s:
public static void main(String[] args) throws Exception {
final List<Map<String, String>> cavia = new ArrayList<Map<String, String>>() {{
add(new HashMap<String, String>() {{
put("key1", "value1");
put("key2", "value2");
put("key3", "value3");
put("key4", "value4");
}});
add(new HashMap<String, String>() {{
put("key5", "value5");
put("key6", "value6");
put("key7", "value7");
put("key8", "value8");
}});
add(new HashMap<String, String>() {{
put("key1", "value1!");
put("key5", "value5!");
}});
}};
cavia
.stream()
.collect(HashMap::new, HashMap::putAll, HashMap::putAll)
.entrySet()
.forEach(System.out::println);
}
Will output:
key1=value1!
key2=value2
key5=value5!
key6=value6
key3=value3
key4=value4
key7=value7
key8=value8
回答3:
A very simple way would be to just use putAll
:
Map<String, String> result = new HashMap<>();
response.forEach(result::putAll);
If you particularly want to do this in a single stream operation then use a reduction:
response.stream().reduce(HashMap<String, String>::new, Map::putAll);
Or if you really want to use flatMap
:
response.stream().map(Map::entrySet).flatMap(Set::stream)
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, Map::putAll));
Note the merging function in the final alternative.
来源:https://stackoverflow.com/questions/46964641/convert-list-of-map-to-map-using-flatmap