Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Java equivalent to Python's reduce function?

Similar questions have been asked, here and here, but given the advent of Java 8, and the generally outdated nature of these questions I'm wondering if now there'd be something at least kindred to it?

This is what I'm referring to.

like image 277
Legato Avatar asked Jan 08 '15 14:01

Legato


2 Answers

You can use a lambda and Stream.reduce, there is a page in the docs dedicated to reductions:

Integer totalAgeReduce = roster
   .stream()
   .map(Person::getAge)
   .reduce(
       0,
       (a, b) -> a + b);
like image 78
elyase Avatar answered Oct 01 '22 23:10

elyase


This is the example used in the Python docs implemented with Java 8 streams:

List<Integer> numbers = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 });
Optional<Integer> sum = numbers.stream().reduce((a, b) -> a + b);
System.out.println(sum.get());
like image 31
Michi Gysel Avatar answered Oct 01 '22 23:10

Michi Gysel