I am new to Java 8
and did find some ways to do addition
, multiply
and subtraction
. I will be posting question for add only.
I have written below code and gathering output in Sum1 and Sum2. Both the methods reduce(0, Integer::sum)
and .reduce(0, (a, b) -> a+b);
gives the same result. What would be the best method to use performance wise and if using large integer values and why ?
List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
Integer sum1 = numbers.stream().reduce(0, (a, b) -> a+b);
System.out.println("SUM ="+sum1);
Integer product = numbers.stream().reduce(0, (a, b) -> a*b);
System.out.println("PRODUCT = "+product);
int sum2 = numbers.stream().reduce(0, Integer::sum);
System.out.println("SUM 2= "+sum2);
Optional<Integer> sum3 = numbers.stream().reduce((a, b) -> (a + b));
System.out.println("SUM3="+sum3);
// Updated as per @Hadi J comment
int sum4 = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println("Sum ="+sum4);