Count how many times a value is referenced in a grid I've got list of points: List&lt;Point&gt; seedPoints. Each Point contains x and y coordinates pointing to certain double value (let's call it pointValue). I would like to display how many times each pointValue is referenced in seedPoints list. To do so I've created following lambda expression:

seedPoints.stream()
    .collect(Collectors.groupingBy(p -&gt;  pointGrid.get(p.x, p.y)))
    .entrySet()
    .stream()
    .map(entry -&gt; "value:" + entry.getKey() + "   count: " + entry.getValue().size())
    .forEach(System.out::println);


The solution works fine, I get the following output:

value:0.0   count: 1
value:3.0   count: 2
value:4.0   count: 1
value:5.0   count: 4
value:6.0   count: 2


I don't find it very clean however. This solution requires two call to the stream() method (1st and 4th line of code), as collect() method is a terminal operation. Does anybody has any idea how could I improve my lambda expression?
There is no intermediate operation that groups items by key.

But in your example there are some changes that can make code more readable.


Instead of collectiing to Map&lt;Double, List&lt;Point&gt;&gt; you could collect directly to Map&lt;Double, Long&gt;

.collect(groupingBy(p -&gt;  pointGrid.get(p.x, p.y), counting()))

Instead of creating stream and performing output just use forEach on a map

.forEach((value, count) -&gt; System.out.println("value :" + value + " count: " + count);



So together it looks like

seedPoints.stream()
    .collect(groupingBy(p -&gt;  pointGrid.get(p.x, p.y), counting()))
    .forEach((value, count) -&gt; System.out.println("value :" + value + " count: " + count);