Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java stream returning a Map

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:-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading