0

I have a DTO with few attributes such as id, name, desc, etc.

It has getters and setters for all its attributes.

I get a Page<MyDto> from the service which I need to group the DTOs based on name attribute.

First, I convert the Page<MyDto> to List<MyDto> by using page.getContent.

I need to convert this List into a Map<String, Object> (not Map<String,String>) by grouping the same names using Java8.

I found some examples but they didn't resolve my problem.

How can I group the MyDto list into a Map?

where the keys are the names (String), and values would be an Array<MyDto> for each name.

For example:

If `List<MyDto>` is : 
[
{"id":1, "name":"albert", "desc":"science"},
{"id":2, "name":"george", "desc":"econ"},
{"id":3, "name":"christ", "desc":"math"},
{"id":4, "name":"george", "desc":"literature"} // george repeats twice
]

The output Map should be:

{

"george":

[
{"id":2, "name":"george", "desc":"econ"},
{"id":4, "name":"george", "desc":"literature"} 
],


"christ":

[
{"id":3, "name":"christ", "desc":"math"}
],


"albert":

[
{"id":1, "name":"albert", "desc":"science"}
]

}
halfer
  • 19,824
  • 17
  • 99
  • 186
Mohammed Idris
  • 768
  • 2
  • 9
  • 26

1 Answers1

5

Simply use Collectors::groupingBy and pass method reference to MyDto::getName method which will be used as the key for your map:

List<MyDto> dtos = ...
Map<String, List<MyDto>> map = dtos.stream()
            .collect(Collectors.groupingBy(MyDto::getName));
Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63