我正在尝试获取一个数字列表,过滤掉偶数,然后对这些偶数进行平方,以便原始列表中的偶数进行平方。这是我的代码:
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));
尝试了其他一些事情,但这就是我目前所处的位置
最佳答案
您需要对结果执行一些操作,例如将其存储在数组中。另请注意,您不需要初始列表,可以直接从流开始:
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
或者您可以决定打印结果:
IntStream.range(0, 100000)
.filter(p -> p % 2 == 0)
.mapToLong(p -> (long) Math.pow(p, 2))
.forEach(System.out::println);
关于java - 使用 lambda 表达式计算偶数的平方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23520703/