Home > Software design >  Trying to create the distinct of items in Map using Java streams
Trying to create the distinct of items in Map using Java streams

Time:10-31

I have a List<Child>, which I want to iterate and create a Map<Long, List<Child>> by taking the distinct values (distinct of parent_id).

Sample data:

**Parent table:**
project_id  project_desc
1             One
2             Two

**child table:**
child_id  parent_id  code
1           1         code1
2           1         code2
3           1         code3
4           2         code4
4           2         code5

I tried with the below code, but it is throwing the exception

List<Child> childEntityList = // initializing the list

Map<Long, List<ChildEntity>> childEntityMap = childEntityList.stream()
    .collect(toMap(
        childEntity ->  childEntity.getParent().getParentId(), 
        childEntity ->  childEntity
    ));

CodePudding user response:

You're using a wrong Collector.

Because you need to associate each Key with a group of Values (not with a single value) the right choice would Collector groupingBy().

You need the flavor of groupingBy() which expects only one argument - classifier function, which tells how to extract the key from the stream element. By default, values mapped to the same key would be stored into a list.

Map<Long, List<Child>> map = childEntityList.stream().
    collect(Collectors.groupingBy(
        childEntity ->  childEntity.getParent().getParentId()
    ));
  • Related