Program to find sum of even number without sum method?

There are following way to find sum of even number without sum method.

Using reduce() method :-

  • First convert Arrays to list using Arrays.asList method
  • Now get the Stream data from List using arrayList.stream() method
  • From filter we find the even number which number divided by 2.
  • In reduce operation first argument to the operator is the return value of the previous application and second argument is the current stream element.
  • Print the value in double type.

syntax :- T reduce(T identity, BinaryOperator<T> accumulator);

				
					import java.util.Arrays;
import java.util.List;

public class ListQ {
	public static void main(String[] args) {

		List<Integer> f = Arrays.asList(1, 2, 3, 4, 5, 6, 1, 2, 3);
		Double r = f.stream().filter(i -> i % 2 == 0).reduce(0, (a, b) -> a + b).doubleValue();
		System.out.println("sum of even number without sum method :- "+r);
	}
}
				
			

Output :-
sum of even number without sum method :- 14.0