Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Processing a list of Map<String,List<Object>> in java 8

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]}

like image 612
Chirag Avatar asked Dec 11 '22 01:12

Chirag


2 Answers

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"));
like image 123
YCF_L Avatar answered Dec 22 '22 00:12

YCF_L


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"));
like image 36
Lino Avatar answered Dec 21 '22 22:12

Lino