'Java stream: using Collectors to grouBy Map

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 ?



Solution 1:[1]

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()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Louis Wasserman