patternjavaMinor
Count how many times a value is referenced in a grid
Viewed 0 times
howreferencedgridvaluetimesmanycount
Problem
I've got list of points:
The solution works fine, I get the following output:
I don't find it very clean however. This solution requires two call to the
List 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: 2I 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?Solution
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
-
Instead of creating stream and performing output just use
So together it looks like
But in your example there are some changes that can make code more readable.
-
Instead of collectiing to
Map> you could collect directly to Map.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);Code Snippets
.collect(groupingBy(p -> pointGrid.get(p.x, p.y), counting())).forEach((value, count) -> System.out.println("value :" + value + " count: " + count);seedPoints.stream()
.collect(groupingBy(p -> pointGrid.get(p.x, p.y), counting()))
.forEach((value, count) -> System.out.println("value :" + value + " count: " + count);Context
StackExchange Code Review Q#136554, answer score: 7
Revisions (0)
No revisions yet.