Java stream returning a Map

Viewed 93

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;
2 Answers

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:

    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)));

You can get Map<String, Integer> map using following code

        Map<String, Integer> colorToCountMap = dresses.stream().
        .collect(Collectors.toMap(Dress::getColor, e -> 1, Math::addExact));
Related