Stream的意义
实例玩转Stream
一、创建一个勾股数流
public static Stream<int[]> getGGStream(int maxLength) {
return IntStream.rangeClosed(5, maxLength)
.boxed()
.flatMap(c -> IntStream.range(1, c)
.mapToObj(a -> new double[]{a, Math.sqrt(c * c - a * a), c})
.filter(t -> t[1] % 1 == 0 && t[0] < t[1]))
.map(d -> new int[]{(int) d[0], (int) d[1], (int) d[2]});
}
二、创建一个斐波那契数列流
public static Stream<Integer> getFiboStream() {
return Stream.iterate(new int[]{0, 1}, t -> new int[]{t[1], t[0] + t[1]})
.map(t -> t[0]);
}
三、创建一个标准质数流
public static Stream<Integer> getPrimeStream() {
return Stream.iterate(2, v -> v == 2 ? ++v : v + 2)
.filter(MyStream::isPrime);
}
public static boolean isPrime(int candidate) {
return IntStream.rangeClosed(2, (int) Math.sqrt(candidate))
.filter(p -> p == 2 || p % 2 == 1)
.noneMatch(p -> candidate % p == 0);
}