Use Collectors to convert List to Map of Objects - Java
Use mapping
as:
public Map<String, List<Team>> groupedByTeams(List<? extends GenericDAO> daoList) {
Map<String, List<Team>> teamMap = daoList.stream()
.collect(Collectors.groupingBy(GenericDAO::getTeam,
Collectors.mapping(this::convertGenericDaoToTeam, Collectors.toList())));
return teamMap;
}
where a conversion such as convertGenericDaoToTeam
could be possibly like:
Team convertGenericDaoToTeam(GenericDAO genericDAO) {
return new Team(genericDAO.getId(), genericDAO.getName(), genericDAO.getType());
}
Your current collector - .collect(Collectors.groupingBy(GenericDAO::getTeam))
- is generating a Map<String,List<? extends GenericDAO>>
.
In order to generate a Map<String, List<Pojo>>
, you have to convert your GenericDAO
instances into Pojo
instances by chaining a Collectors.mapping()
collector to the Collectors.groupingBy()
collector:
Map<String, List<Pojo>> teamMap =
daoList.stream()
.collect(Collectors.groupingBy(GenericDAO::getTeam,
Collectors.mapping (dao -> new Pojo(...),
Collectors.toList())));
This is assuming you have some Pojo
constructor that receives a GenericDAO
instance or relevant GenericDAO
properties.