实例玩转jdk8的Stream

Stream的意义

  • 对集合(Collection)对象功能进行增强,它专注于对集合对象进行各种非常便利、高效的聚合操作
  • 借助于Lambda 表达式,极大的提高编程效率和程序可读性
  • 函数式调用,链式调用的充分发挥
  • 函数式语言+多核时代综合影响的产物


实例玩转Stream

一、创建一个勾股数流

/**
 * 创建一个勾股数流
 *
 * @param maxLength 直角三角形斜边最大值
 * @return 一个勾股数流
 */
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]});
}

二、创建一个斐波那契数列流

/**
 * 创建一个斐波那契数列流
 * @return 斐波那契数列流
 */
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]);
}

三、创建一个标准质数流

/**
 * 创建一个标准质数流
 * @return 标准质数流
 */
public static Stream<Integer> getPrimeStream() {
    return Stream.iterate(2, v -> v == 2 ? ++v : v + 2)
            .filter(MyStream::isPrime);
}

/**
 * 判断指定数是否为质数
 * @param candidate 待判断的数
 * @return 判断数为质数返回true, 否则返回false
 */
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);
}

猜你喜欢

转载自blog.csdn.net/weixin_43566469/article/details/84891345