Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading