Here are 3 ways to find the maximum number inside a list with lambda in Java:
- To use Stream.reduce operation and Integer.max as the associative function. In the end, we use Optional.get() to access the element.
- To use Stream.max with Integer::compareTo. In the end, we use Optional.get() to access the element.
- To use Stream.collect with Collectors.maxBy(Integer::compare) as the collector parameter. In the end, we use Optional.get() to access the element.
import java.util.List;
import java.util.stream.Collectors;
public class MainFindBiggestNumber {
public static void main(String[] args) {
List<Integer> list = List.of(10, 5, -10, 21, 56, 32, 23);
// Using reduce method
Integer maxWithReduce = list.stream().reduce((x, y) -> Integer.max(x, y)).get();
System.out.println("max number using reduce: " + maxWithReduce);
// using max method
Integer maxWithMax = list.stream().max(Integer::compareTo).get();
System.out.println("max number with max: " + maxWithMax);
// using collector
Integer maxWithCollector = list.stream()
.collect(Collectors.maxBy(Integer::compare)).get();
System.out.println("max number with collector: " + maxWithCollector);
}
}
max number using reduce: 56
max number with max: 56
max number with collector: 56