6
\$\begingroup\$

I've got list of points: List<Point> 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 ->  pointGrid.get(p.x, p.y)))
    .entrySet()
    .stream()
    .map(entry -> "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?

\$\endgroup\$
0

1 Answer 1

7
\$\begingroup\$

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<Double, List<Point>> you could collect directly to Map<Double, Long>

    .collect(groupingBy(p ->  pointGrid.get(p.x, p.y), counting()))
    
  • Instead of creating stream and performing output just use forEach on a map

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

So together it looks like

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.