Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
import java.util.*; import java.util.stream.*; public class StreamReduceDemo { public static void main(String[] args) { List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // reduce: sum int sum = numbers.stream() .reduce(0, Integer::sum); System.out.println("Sum: " + sum); // reduce: product long product = numbers.stream() .reduce(1, (a, b) -> a * b); System.out.println("Product: " + product); // IntStream — no boxing IntSummaryStatistics stats = numbers.stream() .mapToInt(Integer::intValue) .summaryStatistics(); System.out.printf("Count=%d, Sum=%d, Min=%d, Max=%d, Avg=%.1f%n", stats.getCount(), stats.getSum(), stats.getMin(), stats.getMax(), stats.getAverage()); // partitioningBy Map<Boolean, List<Integer>> evenOdd = numbers.stream() .collect(Collectors.partitioningBy(n -> n % 2 == 0)); System.out.println("Even: " + evenOdd.get(true)); System.out.println("Odd: " + evenOdd.get(false)); // IntStream.range int sumTo100 = IntStream.rangeClosed(1, 100).sum(); System.out.println("Sum 1..100 = " + sumTo100); // flatMap: flatten nested lists List<List<Integer>> nested = List.of(List.of(1,2), List.of(3,4), List.of(5)); List<Integer> flat = nested.stream() .flatMap(Collection::stream) .collect(Collectors.toList()); System.out.println("Flattened: " + flat); } }
Result
Open