Java Stream API: Summing with reduce() Method

Ever wondered how to transform a collection of data into a single, powerful result with just a few lines of code? Enter the reduce() method in Java’s Stream API – your secret weapon for folding streams into summaries like sums, products, or custom aggregates! Imagine you have a list of numbers [2, 3, 4, 5, 6]. Using reduce(), we can sum them up starting from an initial value of 0. List<Integer> numbers = Arrays.asList(2, 3, 4, 5, 6); Optional<Integer> sum = numbers.stream() .reduce(0, (x, y) -> x + y); System.out.println(sum.get()); // Output: 20 #Java #StreamAPI #FunctionalProgramming #JavaTips #SoftwareDevelopment

  • diagram

To view or add a comment, sign in

Explore content categories