Combine list of list into map using stream

Tags: , ,



I’m trying to convert a pojo object that looks like

[
  {
    "type": "Preferred",
    "ids": ["A", "B", "C"]
   },
  {
    "type": "Non-preferred",
    "ids": ["D", "E"]
  },
  {
    "type": "Popular",
    "ids": ["A", "D"]
  }
]

into Map<String, List<String>>, such as:

{
 "A": ["Preferred", "Popular"],
 "B": ["Preferred"],
 "C": ["Preferred"],
 "D": ["Non-preferred", "Popular"],
 "E": ["Non-preferred"],
}

how can I accomplish this using stream? I preferably want to utilize stream into collect(), instead of using forEach() (which is basically a for-loop).

Thanks in advance.

EDIT: The pojo class looks something like:

class Pojo {
 String type;
 List<String> ids;
}

And I basically have List<Pojo>

Answer

You can do it using stream, create entry for each type and id combination and then do a group by

Map<String, List<String>> results = lists.stream()
            .flatMap(obj->obj.getIds()
                    .stream()
                    .map(id->new AbstractMap.SimpleEntry<>(id,obj.getType())))
            .collect(Collectors.groupingBy(Map.Entry::getKey,
                    Collectors.mapping(Map.Entry::getValue,Collectors.toList())));

 


Source: stackoverflow