Reputation: 911
I have the following Dto class:
@AllArgsConstructor
@ToString
@Getter
public class Dto {
private String cityName;
private String personName;
}
I want to create a Map<String, List> from a List of above Dtos. Logic is such that all the Dtos having same city should be listed together with that city name as key. It can be done using normal foreach easily, but I wanted to know if this can be done using Java 8.
Can something be done using computeIfAbsent, computeIfPresent, stream.collect(toMap()) etc?
public class Runner {
public static void main(String[] args) {
Map<String, List<Dto>> map = new HashMap<>();
List<Dto> tempList = null;
List<Dto> dtos = Arrays.asList(
new Dto("Indore", "A"),
new Dto("Indore", "B"),
new Dto("Pune", "C"),
new Dto("Pune", "D")
);
for (Dto dto : dtos) {
if(map.containsKey(dto.getCityName())) {
map.get(dto.getCityName()).add(dto);
}
else {
tempList = new ArrayList<>();
tempList.add(dto);
map.put(dto.getCityName(), tempList);
}
}
System.out.println(map);
}
}
Upvotes: 0
Views: 162
Reputation: 140494
The easiest way is:
Map<String, List<Dto>> map = dtos.stream().collect(Collectors.groupingBy(Dto::getCityName));
The way most similar to your current code would be:
for (Dto dto : dtos) {
map.computeIfAbsent(dto.getCityName(), k -> new ArrayList<>()).add(dto);
}
Upvotes: 8