英文:
Is there a Java 8 way to populate the following map?
问题
以下是已翻译的代码部分:
@AllArgsConstructor
@ToString
@Getter
public class Dto {
private String cityName;
private String personName;
}
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);
}
}
希望这对你有所帮助。如果你有任何其他问题,请随时提出。
英文:
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<Dto>> 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);
}
}
答案1
得分: 8
最简单的方法是:
Map<String, List<Dto>> map = dtos.stream().collect(Collectors.groupingBy(Dto::getCityName));
与您当前代码最相似的方式是:
for (Dto dto : dtos) {
map.computeIfAbsent(dto.getCityName(), k -> new ArrayList<>()).add(dto);
}
英文:
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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论