使用lambda表达式平均偶数

Pen*_*mer 2 java lambda java-8

我正在尝试获取一个数字列表,过滤掉偶数,然后对这些偶数进行平方,以便原始列表中的偶数是平方的.这是我的代码:

ArrayList<Long> nums2 = new ArrayList<Long>();
for(long i = 0; i < 100000; i++) 
    nums2.add(i);
nums2.stream().filter(p -> p%2 == 0).forEach(p -> p = (long)Math.pow(p, 2));
Run Code Online (Sandbox Code Playgroud)

尝试了其他一些事情,但这是我到目前为止的地方

ass*_*ias 6

您需要对结果执行某些操作,例如将其存储在数组中.另请注意,您不需要初始列表,可以直接从流开始:

long[] result = IntStream.range(0, 100000) //instead of your initial list
    .filter(p -> p % 2 == 0)               //filters
    .mapToLong(p -> (long) Math.pow(p, 2)) //"replaces" each number with its square
    .toArray();                            //collect the results in an array
Run Code Online (Sandbox Code Playgroud)

或者您可以决定打印结果:

IntStream.range(0, 100000)
    .filter(p -> p % 2 == 0)
    .mapToLong(p -> (long) Math.pow(p, 2))
    .forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)