Home > Enterprise >  Java stream: using Collectors to grouBy Map
Java stream: using Collectors to grouBy Map

Time:03-15

I would like to transform:

Map<Integer, List<Integer>> result =
  dre.getItems().stream().collect(
    Collectors.groupingBy(DashboardEntity::getElementNumber,
      Collectors.mapping(DashboardEntity::getTotalElement , Collectors.toList())
    )
  );

into (naive):

Map<Integer, List<String>> result =
  dre.getItems().stream().collect(
    Collectors.groupingBy(DashboardEntity::getElementNumber,
      Collectors.mapping(DashboardEntity::getTotalElement   "_" DashboardEntity::getDate, Collectors.toList())
    )
  );

But the latter would raise a compile time error:

Method reference expression is not expected here

What would be the way to get result of type Map<Integer, Map<String, Integer>>, where the Map<String, Integer> key would contain the date (getDate call) and the value totalElement (getTotalElement call) value, knowing that the relation between date and totalElement is 1..1 ?

CodePudding user response:

You have to use a lambda; you can't use method references this way.

DashboardEntity::getTotalElement   "_" DashboardEntity::getDate

should be

entity -> entity.getTotalElement()   "_"   entity.getDate()
  • Related