Skip to content

Instantly share code, notes, and snippets.

@adityachaudhari
Last active October 17, 2021 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adityachaudhari/c0e344d64f8504be424c14c4c2486c9d to your computer and use it in GitHub Desktop.
Save adityachaudhari/c0e344d64f8504be424c14c4c2486c9d to your computer and use it in GitHub Desktop.
reduce in java 8 understanding example code
package com.java8.streams;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class ReduceUnderstanding {
public static void main(String[] args) {
List<Integer> listOfNumbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// sum of numbers without reduce
int sum = 0;
for (int x : listOfNumbers) {
sum += x;
}
System.out.println("sum of numbers without using reduce " + sum);
// with using reduce
//Integer sumOfNumbers = listOfNumbers.stream().reduce(0,(a,b) -> a+b);
Integer sumOfNumbers = listOfNumbers.stream().reduce(0, Integer::sum);
System.out.println("sum of numbers with reduce used : " + sumOfNumbers);
// count no of dishes in stream using the map and reduce.
Integer noOfDIshes = Dish.menu.stream()
// map each dish in a stream as integer 1 if we have {Dish1.Dish2,Dish3} stream then it ll map to {1,1,1}
.map(dish -> 1).reduce(0, (a, b) -> a + b);
System.out.println("No of dishes using map and reduce : " + noOfDIshes);
// OOTB count implementation below is using reduce internally
System.out.println("No of dishes using count method on streams: " + Dish.menu.stream().count());
//using reduce to find maximum integer in given integer values
//Optional<Integer> maxNo = listOfNumbers.stream().reduce((var0, var1) -> var0 >= var1 ? var0 : var1);
Optional<Integer> maxNo = listOfNumbers.stream().reduce(Integer::max);
System.out.println("Find Max integer usnig reduce : " + (maxNo.isPresent() ? maxNo.get() : 0));
}
}
Output :
sum of numbers without using reduce 55
sum of numbers with reduce used : 55
No of dishes using map and reduce : 9
No of dishes using count method on streams: 9
Find Max integer usnig reduce : 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment