Java Reference
In-Depth Information
3 . This counts the number of items in each partition, resulting in the following Map:
{false=5, true=4}
To give one last example of how you can use the partitioningBy collector, we'll put aside the
menu data model and look at something a bit more complex but also more interesting:
partitioning numbers into prime and nonprime.
6.4.2. Partitioning numbers into prime and nonprime
Suppose you want to write a method accepting as argument an int n and partitioning the first n
natural numbers into prime and nonprime. But first, it will be useful to develop a predicate that
tests to see if a given candidate number is prime or not:
A simple optimization is to test only for factors less than or equal to the square root of the
candidate:
public boolean isPrime(int candidate) {
int candidateRoot = (int) Math.sqrt((double) candidate);
return IntStream.rangeClosed(2, candidateRoot)
.noneMatch(i -> candidate % i == 0);
}
Now the biggest part of the job is done. To partition the first n numbers into prime and
nonprime, it's enough to create a stream containing those n numbers and reduce it with a
partitioningBy collector using as predicate the isPrime method you just developed:
public Map<Boolean, List<Integer>> partitionPrimes(int n) {
return IntStream.rangeClosed(2, n).boxed()
.collect(
partitioningBy(candidate -> isPrime(candidate)));
}
Search WWH ::




Custom Search