Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package java8.streams;
- import java.util.Arrays;
- import java.util.List;
- public class ReduceTest {
- static class Person implements Comparable<Person> {
- String name;
- int age;
- Person(String name, int age) {
- this.name = name;
- this.age = age;
- }
- @Override
- public String toString() {
- return name;
- }
- @Override
- public int compareTo(Person other) {
- if(this.age == other.age) return 0;
- else return ((this.age > other.age) ? 1 : -1);
- }
- }
- public static void main(String[] args) {
- List<Person> persons =
- Arrays.asList(
- new Person("Max", 18),
- new Person("Peter", 23),
- new Person("Pamela", 23),
- new Person("David", 12));
- // Reduces a stream of elements to exactly one element of the stream
- persons
- .stream()
- .reduce((p1, p2) -> p1.age > p2.age ? p1 : p2)
- .ifPresent(System.out::println); // Pamela
- // method accepts both an identity value and a BinaryOperator accumulator. This method can be utilized to construct a new
- Person result =
- persons
- .stream()
- .reduce(new Person("",0), (p1, p2) -> {
- p1.age += p2.age;
- p1.name += p2.name;
- return p1;
- });
- System.out.format("name=%s; age=%s", result.name, result.age);
- System.out.println();
- System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
- // The third reduce method accepts three parameters: an identity value, a BiFunction accumulator and a combiner function of type BinaryOperator
- Integer ageSum = persons
- .stream()
- .reduce(0, (sum, p) -> sum += p.age, (sum1, sum2) -> sum1 + sum2);
- System.out.println(ageSum); // 76
- System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
- //Third reduce in details
- Integer ageSumDtails = persons
- .stream()
- .reduce(0,
- (sum, p) -> {
- System.out.format("accumulator: sum=%s; person=%s\n", sum, p);
- return sum + p.age;
- },
- (sum1, sum2) -> {
- System.out.format("combiner: sum1=%s; sum2=%s\n", sum1, sum2);
- return sum1 + sum2;
- });
- System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
- // Combiner getting called in .parallelStream()
- //Third reduce in details
- Integer ageSumParallel = persons
- .parallelStream()
- .reduce(0,
- (sum, p) -> {
- System.out.format("accumulator: sum=%s; person=%s\n", sum, p);
- return sum + p.age;
- },
- (sum1, sum2) -> {
- System.out.format("combiner: sum1=%s; sum2=%s\n", sum1, sum2);
- return sum1 + sum2;
- });
- }
- }
Add Comment
Please, Sign In to add comment