Streams Reduction

PHOTO EMBED

Thu Jun 06 2024 02:41:37 GMT+0000 (Coordinated Universal Time)

Saved by @chatgpt #java

import java.util.*;

import java.util.stream.*;

public class ReductionDemo {

    public static void main(String[] args) {

        ArrayList<Integer> al = new ArrayList<>();

        al.add(10);

        al.add(20);

        al.add(30);

        al.add(40);

        al.add(50);

        System.out.println("Contents of the collection: " + al);

        System.out.println();

        Optional<Integer> obj1 = al.stream().reduce((x, y) -> (x + y));

        if(obj1.isPresent())

            System.out.println("Total is: " + obj1.get());

        System.out.println();

        long product = al.stream().reduce(1, (x, y) -> (x * y));

        System.out.println("Product is: " + product);

    }

}
content_copyCOPY