How do I use Collectors in order to convert a list of DAOs, to a Map<String, List<Pojo>>
daoList looks something like this:
[0] : id = "34234", team = "gools", name = "bob", type = "old"
[1] : id = "23423", team = "fool" , name = "sam", type = "new"
[2] : id = "34342", team = "gools" , name = "dan", type = "new"
I want to groupBy 'team' attribute and have a list for each team, as follows:
"gools":
["id": 34234, "name": "bob", "type": "old"],
["id": 34342, "name": "dan", "type": "new"]
"fool":
["id": 23423, "name": "sam", "type": "new"]
Pojo looks like this:
@Data
@NoArgsConstructor
@AllArgsConstructor(access = AccessLevel.PUBLIC)
public class Pojo{
private String id;
private String name;
private String type;
}
This is how I'm trying to do that, obviously the wrong way:
public Team groupedByTeams(List<? extends GenericDAO> daoList)
{
Map<String, List<Pojo>> teamMap= daoList.stream()
.collect(Collectors.groupingBy(GenericDAO::getTeam))
}
With Java 8, you can convert a List to Map in one line using the stream() and Collectors. toMap() utility methods. The Collectors. toMap() method collects a stream as a Map and uses its arguments to decide what key/value to use.
Array List can be converted into HashMap, but the HashMap does not maintain the order of ArrayList. To maintain the order, we can use LinkedHashMap which is the implementation of HashMap.
Converting a list to stream is very simple. As List extends the Collection interface, we can use the Collection. stream() method that returns a sequential stream of elements in the list.
In Java, you can use the Jackson library to convert a Java object into a Map easily.
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.
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With