How can I get the following problem solved using Java Streams?
Given:-
class Dress {
private String brandName;
private String color;
public String getBrandName() {
return brandName;
}
public String getColor() {
return color;
}
}
List<Dress> dresses = getDresses(); // API call
Required:-
// Number of dresses per color
Map<String, Integer> colorToCountMap;
>Solution :
If you can live with Long instead of Integer, you can use Collectors.counting() as downstream collector:
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));
}
If it has to be Integer, you can use Collectors.summingInt(x -> 1) as mentioned in the comments.