I am trying to create a single map from list of maps. Which contains only key "1" and all the values of key "1" across different maps under that list using Java 8 stream API.
List<Map<String,Object>> list=new ArrayList<>();
Map<String,Object> map1=new HashMap<>();
map1.put("1", Arrays.asList(new String[] {"A"}));
map1.put("2", Arrays.asList(new String[] {"B"}));
Map<String,Object> map2=new HashMap<>();
map2.put("1", Arrays.asList(new String[] {"C"}));
map2.put("2", Arrays.asList(new String[] {"D"}));
Required output :- {1=[A, C]}
Because you have only one entry, then in this case, you need just to focus on the values, and for the key you can just use "1"
, for that you can create a Map like this :
Map<String, List<String>> result = new HashMap<>();
result.put("1", list.stream()
.filter(e -> e.containsKey("1"))
.flatMap(e -> e.values().stream())
.flatMap(List::stream)
.collect(Collectors.toList()));
Or as stated by Lino in the comment, you can also use :
Map<String, List<String>> result = list.stream()
.filter(e -> e.containsKey("1"))
.flatMap(e -> e.values().stream())
.flatMap(List::stream)
.collect(Collectors.groupingBy(t -> "1"));
As mentioned by @ernest_k you should declare
list
as:List<Map<String, List<String>>>
You can use a groupingBy
collector:
Map<String, List<String>> result = list.stream()
.map(m -> m.get("1"))
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.collect(Collectors.groupingBy(t -> "1"));
You can get rid of the intermediate filter
with this. But this may be more confusing (and effectively does the same):
Map<String, List<String>> result = list.stream()
.map(m -> m.get("1"))
.flatMap(l -> l == null ? Stream.empty() : l.stream())
.collect(Collectors.groupingBy(t -> "1"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With