Trying to find out sum of square of only even numbers from integers list using java 8 stream api [duplicate]

I'm trying to take a list of numbers, filter out the even numbers and then square those even numbers so that the even numbers in the original list are squared. Here's my code:

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));

Tried a couple other things, but this is where I'm at so far


Solution 1:

You need to do something with the result, for example store it in an array. Also note that you don't need the initial list and can start with a stream directly:

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

Or you could decide to print the result:

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

Solution 2:

An alternative solution would be mapping the results and collecting them into a List using Collectors#toList:

List<Long> results = nums2.stream()
    .filter(p -> p%2 == 0)
    .map(p -> p = (long)Math.pow(p, 2))
    .collect(Collectors.toList());