Popular Feed

Java8 find the sum of even numbers square using lambda expression

Below are the code to get sum of even numbers square using lambda expression.

public static void main(String[] args) {
		 List<Integer> listInt = Arrays.asList(1, 2, 3, 4, 5);
		 IntSummaryStatistics summaryStatistics= listInt.stream().
		 filter((i)->i%2==0 ).mapToInt((i)->+i*i).summaryStatistics();
		 System.out.println(summaryStatistics.getSum());
	}
In line 2 we have created a list of integer and assign it to a variable called listInt.
In line 3 we created a return type IntSummaryStatistics
On the right side we created a stream listInt.stream(of that list .
In line 3 we applied a filter which is filtering only even numbers filter((i)->i%2==0 ). 
Filter() accepts predicate as a argument , predicate interface given below to check the condition and return boolean response. Its a functional interface  has a method called test which takes a parameter and return boolean response.
@FunctionalInterface
public interface Predicate<T> {
  boolean test(T t);
}
after that we mapped the result in Int type and while mapping the result we square all the even numbers mapToInt((i)->+i*i). At last we called the summary statistics and collect the entire data   summaryStatistics();
In line 4 we used the collected data and get the sum of all values. 
Find more about streams basics in the link.

No comments: