首页 > 解决方案 > 如何使用流和 lambda 从 int[] 数组中打印和选择数字

问题描述

我的目标是从数组中读取和选择数字,然后将大于 0 的数字打印出来,这是我的代码示例:

public class LambdaTest {
    private int[] num = new int[10];

    public static void main(String[] args) {
        LambdaTest test = new LambdaTest();
        //Lista de números a ordenar
        test.num[0] = 5;
        test.num[1] = -6;
        test.num[2] = 7;
        test.num[3] = 23;
        test.num[4] = -1;
        test.num[5] = 55;
        test.num[6] = 78;
        test.num[7] = 45;
        test.num[8] = 31;
        test.num[9] = -67;
        //Proceso normal
        for (int i=0; i<test.num.length; i++){
            if (test.num[i]>=0){
                System.out.println(test.num[i]);
            }
        }
    }
}

但是对于 lambda 表达式和流,在此先感谢

标签: javaarrayslambdainteger

解决方案


你可以做

Arrays.stream(test.num).filter(n -> n >= 0).forEach(System.out::println);

推荐阅读