case 1:
// streams/Randoms.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.*;
public class Randoms {
public static void main(String[] args) {
new Random(47).ints(5, 20).distinct().limit(7).sorted().forEach(System.out::println);
}
}
/* Output:
6
10
13
16
17
18
19
*/
In Randoms.java, distinct() removed duplicates from the stream. Using distinct() is far less work than creating a Set to eliminate duplicates.
case 2:
// streams/Prime.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import static java.util.stream.LongStream.*;
import java.util.stream.*;
public class Prime {
public static boolean isPrime(long n) {
return rangeClosed(2, (long) Math.sqrt(n)).noneMatch(i -> n % i == 0);
// startInclusive - the (inclusive) initial value
// endInclusive - the inclusive upper bound
}
public LongStream numbers() {
return iterate(2, i -> i + 1).filter(Prime::isPrime);
}
public static void main(String[] args) {
// System.out.println(Math.sqrt(4)); // 2.0
new Prime().numbers().limit(10).forEach(n -> System.out.format("%d ", n));
System.out.println();
new Prime().numbers().skip(90).limit(10).forEach(n -> System.out.format("%d ", n));
}
}
/* Output:
2 3 5 7 11 13 17 19 23 29
467 479 487 491 499 503 509 521 523 541
*/
rangeClosed() includes the top boundary value. The noneMatch() operation returns true if no modulus produces zero, and false if any equal zero. noneMatch() quits after the first failure rather than trying them all.
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/Randoms.java
3. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/Prime.java
5. https://docs.oracle.com/javase/8/docs/api/java/util/stream/LongStream.html#rangeClosed-long-long-