Ad Infinitum Ad Infinitum - 3 months ago 10
Java Question

Merging n number of list into a Map based on a value in List

I have the following objects in an

ArrayList
and a value in this object is illustrated as the numbers at the beginning, which are
Id
of something.

enter image description here

I need to create a
Map
object, whose key should be the id of lists and whose values should be the list objects. At the end of the day, I would like to have a Map something like that.

enter image description here

I have already solved this problem with two for loops and lots of
if
statements but it seems very ugly to me.

Any cleaner solution would be appreciated.

Answer
Map<Integer, List<Foo>> result = list.stream().collect(Collectors.groupingBy(Foo::getId));