I retrieve from a JPA Repository query an Entity which refers to these table
Id | Name | City |
---|---|---|
1 | John | New York |
2 | Paul | Atlanta |
3 | Mark | Los Angeles |
4 | Susan | Los Angeles |
5 | Josh | New York |
6 | Charles | Atlanta |
I'd like to group by my List of Entities by City and obtain this response:
{"New York":["John","Josh"],"Atlanta":["Paul", "Charles"],"Los Angeles":["Mark","Susan"]}
I tried to follow This link but I only can obtain a Map<String, List< RegistryEntity >. I didn't want these, I want Map<String, List< String >> so I did in these way.
public Map<String, List<String>> findAllUsers() {
List<RegistryEntity> items = registryRepository.findAll();
Map<String, List<String>> itemsGrouped = new HashMap<>();
for (RegistryEntity s: items) {
if (itemsGrouped.get(s.getCity()) != null) {
itemsGrouped.get(s.getCity()).add(s.getName());
}
else {
List<String> tempResults = new ArrayList<>();
tempResults.add(s.getCity());
itemsGrouped.put(s.getName(), tempResults);
}
}
return itemsGrouped;
}
The code works, but I'd like to know if there's something more efficient and more elegant to group by my entity.
CodePudding user response:
You can use Stream then you need also collectors.groupingBy and collectors.mapping, i tried to code something like down below.
Map<String, List<String>> itemsGrouped =
items.stream()
.collect(Collectors.groupingBy(
RegistryEntity::getCity,
Collectors.mapping(RegistryEntity::getName, Collectors.toList()))
);