App下載
首頁javastream_reduceJava Stream - 如何減少到和數(shù)

Java Stream - 如何減少到和數(shù)

我們想知道如何減少到和數(shù)。
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);
  }
}