I’m trying to find a (functional) way to add a collection of objects into a map that is keyed on a member of these objects.
Let’s say I have the following objects (they’re all instances of the same class O):
o1(a = 1, b = x)
o2(a = 1, b = y)
o3(a = 2, b = z)
I want to generate a Map keyed on member a that contains the following tuples:
(1, List(o1, o2))
(2, List(o3))
Now I could obviously do it iteratively, going through each object in my initial list and adding them as I go along. But I feel I am missing a functional way of doing that easily. I’ve been struggling with maps, flatMaps and filters to try to achieve that, no result so far.
groupByis what you want: