DMcg
DMcg

Reputation: 129

Java Stream Grouping By on Objects with Parent Child Relationship

I have a class like so...

class Data { int id, int parent}

And a list of objects like so...

List<Data> dataList = new ArrayList();
dataList.add(new Data(1,0));
dataList.add(new Data(2,1));
dataList.add(new Data(3,1));
dataList.add(new Data(4,2));
dataList.add(new Data(5,2));

I want to use the streaming api to collect my list into a

Map<Data, List<Data>>

where the key of the map is the parent and the values are the children.

Any help would be greatly appreciated. Thanks

Upvotes: 0

Views: 1935

Answers (1)

Eran
Eran

Reputation: 393771

Collectors.groupingBy() can give you a Map<Integer, List<Data>> where the key is the parent ID:

Map<Integer, List<Data>> map =
    dataList.stream()
            .collect(Collectors.groupingBy(Data::getParent));

If you want the key to be the Data instance that corresponds with the parent ID, you'll need to prepare a mapping of IDs to corresponding Data instances first:

Map<Integer, Data> ids = dataList.stream()
                                 .collect(Collectors.toMap(Data::getID, Function.identity()));

and then:

Map<Data, List<Data>> map =
    dataList.stream()
            .collect(Collectors.groupingBy(d -> ids.get(d.getParent())));

Upvotes: 6

Related Questions