Core Java
core22StreamsDemo
- Path
- pkg1core/core22StreamsDemo.java
- Package
- pkg1core
- Study order
- 23
- Run
- Single-file source launch
- Command
- java pkg1core/core22StreamsDemo.java
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg1core;2 3/*4 * core22StreamsDemo.java5 * ----------------6 * The Streams API: building pipelines of intermediate + terminal operations,7 * and Collectors for grouping/joining/summarizing.8 *9 * EXPLANATION:10 * - Streams are LAZY: intermediate ops (filter/map/sorted) build a pipeline;11 * a terminal op (collect/reduce/forEach/count) triggers execution.12 * - Streams don't mutate the source; prefer pure, stateless functions.13 */14import java.util.*;15import java.util.stream.*;16 17public class core22StreamsDemo {18 19 record Person(String name, String city, int age) {}20 21 public static void main(String[] args) {22 List<Integer> nums = List.of(5, 2, 8, 1, 9, 3, 8, 2);23 24 // filter -> map -> sorted -> distinct -> collect25 List<Integer> result = nums.stream()26 .filter(n -> n > 2)27 .map(n -> n * 10)28 .distinct()29 .sorted()30 .toList();31 System.out.println("pipeline: " + result);32 33 // Numeric streams + statistics34 IntSummaryStatistics stats = nums.stream().mapToInt(Integer::intValue).summaryStatistics();35 System.out.printf("count=%d sum=%d min=%d max=%d avg=%.2f%n",36 stats.getCount(), stats.getSum(), stats.getMin(), stats.getMax(), stats.getAverage());37 38 // reduce39 int product = Stream.of(1, 2, 3, 4).reduce(1, (a, b) -> a * b);40 System.out.println("product 1..4 = " + product);41 42 // Collectors: grouping, partitioning, joining43 List<Person> people = List.of(44 new Person("Alice", "NYC", 30),45 new Person("Bob", "LA", 25),46 new Person("Cara", "NYC", 35),47 new Person("Dan", "LA", 40));48 49 Map<String, List<String>> byCity = people.stream()50 .collect(Collectors.groupingBy(Person::city,51 Collectors.mapping(Person::name, Collectors.toList())));52 System.out.println("grouped by city: " + byCity);53 54 Map<Boolean, List<String>> partition = people.stream()55 .collect(Collectors.partitioningBy(p -> p.age() >= 30,56 Collectors.mapping(Person::name, Collectors.toList())));57 System.out.println("age>=30 partition: " + partition);58 59 Map<String, Double> avgAgeByCity = people.stream()60 .collect(Collectors.groupingBy(Person::city, Collectors.averagingInt(Person::age)));61 System.out.println("avg age by city: " + avgAgeByCity);62 63 String names = people.stream().map(Person::name).collect(Collectors.joining(", ", "[", "]"));64 System.out.println("joined names: " + names);65 66 // Generate / iterate (infinite streams with limit)67 List<Integer> firstFiveSquares = Stream.iterate(1, x -> x + 1).map(x -> x * x).limit(5).toList();68 System.out.println("first 5 squares: " + firstFiveSquares);69 70 // flatMap: flatten nested71 List<List<Integer>> nested = List.of(List.of(1, 2), List.of(3, 4), List.of(5));72 List<Integer> flat = nested.stream().flatMap(List::stream).toList();73 System.out.println("flattened: " + flat);74 75 // anyMatch / allMatch / findFirst76 System.out.println("any > 8? " + nums.stream().anyMatch(n -> n > 8));77 System.out.println("all > 0? " + nums.stream().allMatch(n -> n > 0));78 System.out.println("first even: " + nums.stream().filter(n -> n % 2 == 0).findFirst().orElse(-1));79 }80}