Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.Optional;
import java.util.stream.Stream;

public class Main {

    public static void main(String[] args) {

        // reduce numbers to their sum
        Stream<Integer> numbers = Stream.of(3, 5, 7, 9, 11);
        Optional<Integer> sum = numbers.reduce((x, y) -> x + y);
        sum.ifPresent(System.out::println);

        // reduce numbers to their sum with seed
        numbers = Stream.of(3, 5, 7, 9, 11);
        Integer sumWithSeed = numbers.reduce(0, (x, y) -> x + y);
        System.out.println(sumWithSeed);

        // reduce numbers to their sum with parallel stream
        Stream<String> words = Stream.of("All", "men", "are", "created", "equal");
        Integer lengthOfAllWords = words.reduce(0, (total, word) -> total + word.length(),
                (total1, total2) -> total1 + total2);
        System.out.println(lengthOfAllWords);
    }
}