Master Java Stream Tricks: Null Handling, Infinite Streams & Collectors
This article showcases a collection of over 100 practical Spring Boot 3 examples, focusing on modern Java Stream techniques such as Stream.ofNullable for null safety, Stream.iterate for infinite sequences, advanced collectors like collectingAndThen, takeWhile/dropWhile, teeing, and summarizingLong, each illustrated with concise code snippets.
Spring Boot 3 practical case collection includes over 100 examples, and this article highlights several modern Java Stream features.
1. Stream.ofNullable – Safe handling of null values
Java 9 introduced Stream.ofNullable() which automatically skips null elements, avoiding NullPointerException. Example:
<code>public static void test1() {
List<String> names = Arrays.asList("Spring", null, "Pack", "XG", null);
List<String> filteredNames = names.stream()
.flatMap(Stream::ofNullable) // Bye-bye, nulls!
.collect(Collectors.toList());
System.out.println(filteredNames); // [Spring, Pack, XG]
}</code>2. Stream.iterate – Creating infinite streams
Use Stream.iterate() to generate an unbounded sequence, e.g., an endless list of even numbers.
<code>public static void test2() {
Stream.iterate(2, n -> n + 2)
.limit(5)
.forEach(System.out::println); // 2, 4, 6, 8, 10
}</code>3. Collectors.collectingAndThen – Post‑processing results
Combine collection with a finishing function, such as rounding the average salary of employees.
<code>public record Employee(String name, Double salary) {}
public static void test3() {
List<Employee> employees = List.of(
new Employee("Spring", 6879.6),
new Employee("Java", 16890.0),
new Employee("XG", 8983.5),
new Employee("Pack", 12983.8)
);
long averageSalary = employees.stream()
.collect(Collectors.collectingAndThen(
Collectors.averagingDouble(Employee::salary),
Math::round));
System.err.println("avg: " + averageSalary); // avg: 11434
}</code>4. takeWhile and dropWhile – Precise stream slicing
These methods split a stream based on a predicate.
<code>public static void test4() {
List<Integer> numbers = List.of(1,2,3,4,5,6,7,8);
List<Integer> taken = numbers.stream()
.takeWhile(n -> n < 5)
.collect(Collectors.toList());
System.err.println(taken); // [1, 2, 3, 4]
List<Integer> dropped = numbers.stream()
.dropWhile(n -> n < 5)
.collect(Collectors.toList());
System.err.println(dropped); // [5, 6, 7, 8]
}</code>5. Collectors.teeing – Simultaneous collectors
Java 12’s Collectors.teeing() runs two collectors in parallel and merges their results.
<code>public static void test5() {
List<Integer> numbers = List.of(45,5,3,33,22,6,678,23);
Map<String, Optional<Integer>> minMax = numbers.stream()
.collect(Collectors.teeing(
Collectors.maxBy(Integer::compareTo),
Collectors.minBy(Integer::compareTo),
(max, min) -> Map.of("Max", max, "Min", min)));
System.err.println(minMax); // {Max=Optional[678], Min=Optional[3]}
}</code>6. LongSummaryStatistics – Comprehensive statistics
The summarizingLong collector provides count, sum, min, average, and max in one step.
<code>public static void test6() {
List<Integer> numbers = List.of(45,5,3,33,22,6,678,23);
LongSummaryStatistics stats = numbers.stream()
.collect(Collectors.summarizingLong(Long::valueOf));
System.err.println(stats);
// LongSummaryStatistics{count=8, sum=815, min=3, average=101.875, max=678}
}</code>These examples demonstrate how modern Java Stream APIs can simplify data processing, improve readability, and reduce boilerplate code.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.