atwood-pan

 

Java-14流Stream【创建一个简易for循环工具】

Java-14流Stream

构造简易的循环取代for

IntStream类提供了一个range()方法,可以生成一个流————由int值组成的序列

import static java.util.stream.IntStream.*;

/**
 * IntStream类提供了一个range()方法,可以生成一个流————由int值组成的序列
 */
public class Ranges {
    public static void main(String[] args) {
        // The traditional way:
      	// 传统的for
        int result = 0;
        for (int i = 10; i < 20; i++)
            result += i;
        System.out.println(result);

        // for-in with a range:
      	// 使用range函数的for
        result = 0;
        for (int i : range(10, 20).toArray())
            result += i;
        System.out.println(result);

        // Use streams:
      	// 使用流中的sum()求和
        System.out.println(range(10, 20).sum());
    }
}
/* Output:
145
145
145
*/

简化循环util

那么,我们可不可以自己创造一个专门用于简化for循环的工具呢?

那是当然可以的:

第一步创建一个Range,提供了三种range()方法,类似于IntStream中的

public class Range {
    // Produce sequence [start..end) incrementing by step
    public static int[] range(int start, int end, int step) {
        if (step == 0)
            throw new
                    IllegalArgumentException("Step cannot be zero");
        int sz = Math.max(0, step >= 0 ?
                (end + step - 1 - start) / step
                : (end + step + 1 - start) / step);
        int[] result = new int[sz];
        for (int i = 0; i < sz; i++)
            result[i] = start + (i * step);
        return result;
    }  // Produce a sequence [start..end)

    public static int[] range(int start, int end) {
        return range(start, end, 1);
    }

    // Produce a sequence [0..n)
    public static int[] range(int n) {
        return range(0, n);
    }
}

第二步,为了取代简单的for循环,再创建一个repeat()工具函数:

/**
 * TODO 取代简单的for循环 ==》 repeat() 工具函数
 */
public class Repeat {
    /**
     * 不带步长的循环
     * @param n
     * @param action
     */
    public static void repeat(int n, Runnable action) {
        range(0, n).forEach(i -> action.run());
    }

    /**
     * 带有步长的循环
     * @param n
     * @param action
     * @param step 步长
     */
    public static void repeatStep(int n, Runnable action, int step) {
        range(0, n).forEach(i -> action.run());
    }
}

这样生成的循环可以说更简单了:

import static org.example.onjava.example14.Repeat.*;// 引入简单循环工具类
/**
 * @Author Coder_Pans
 * @Date 2022/11/18 13:37
 * @PackageName:org.example.onjava.example14.stream
 * @ClassName: Looping
 * @Description: TODO 引用简单循环取代for
 * @Version 1.0
 */
public class Looping {
    static void hi(){
        System.out.println("Hi~~~~!");
    }

    public static void main(String[] args) {
        repeat(3, () -> System.out.println("Looping!"));
        repeat(10, () -> System.out.println("Looping!"));
        repeat(2, Looping::hi);
    }
}

posted on 2022-11-18 13:54  JavaCoderPan  阅读(254)  评论(0编辑  收藏  举报

导航