如何使用 Java Streams 解决以下问题?
给定:-
class Dress {
private String brandName;
private String color;
public String getBrandName() {
return brandName;
}
public String getColor() {
return color;
}
}
List<Dress> dresses = getDresses(); // API call
必需:-
// Number of dresses per color
Map<String, Integer> colorToCountMap;
最佳答案
如果您可以使用 Long
而不是 Integer
,则可以使用 Collectors.counting()
作为下游收集器:
private record Dress(String brandName, String color) {}
public static void main(String[] args) {
Map<String, Long> result = Stream.of(new Dress("One", "Red"), new Dress("Two", "Green"), new Dress("Three", "Red"))
.collect(Collectors.groupingBy(Dress::color, Collectors.counting()));
result.forEach((k,v) -> System.out.println(k + ": " + v));
}
如果它必须是 Integer
,您可以使用 Collectors.summingInt(x -> 1)
,如评论中所述:
Map<String, Integer> result = Stream.of(new Dress("One", "Red"), new Dress("Two", "Green"), new Dress("Three", "Red"))
.collect(Collectors.groupingBy(Dress::color, Collectors.summingInt(x -> 1)));
关于返回 Map 的 Java 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72571811/