Sub topic 2
Getting Results: forEach, count, anyMatch, and findFirst
A stream does no work until you ask it for a result. A terminal operation is the last step in a pipeline. It produces the answer and closes the stream.
Common Terminal Operations
forEachruns an action on each element, such as printing it.countreturns how many elements there are.anyMatchreturnstrueif at least one element passes a test.findFirstreturns the first element, if there is one.
Collecting, Sorting, and Limiting
A collector is a recipe that gathers elements into a container. Collectors.toList(), toSet(), toMap(), and joining() build a list, a set, a map, or one string.
Before you collect, you can use three intermediate steps. sorted() puts elements in order. distinct() removes duplicates. limit(n) keeps only the first n elements.
Optional Results
An Optional is a box that holds a value or is empty. findFirst returns one because the stream might have no elements. You can call orElse on it to supply a default value when the box is empty.
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
public class ResultsExample {
public static void main(String[] args) {
List<String> fruits = List.of("pear", "apple", "fig", "apple", "kiwi");
fruits.stream().forEach(System.out::println);
System.out.println(fruits.stream().count()); // 5
System.out.println(fruits.stream().anyMatch(f -> f.equals("fig"))); // true
Optional<String> firstK = fruits.stream()
.filter(f -> f.startsWith("k"))
.findFirst();
System.out.println(firstK.orElse("none")); // kiwi
List<String> topThree = fruits.stream()
.distinct()
.sorted()
.limit(3)
.collect(Collectors.toList());
System.out.println(topThree); // [apple, fig, kiwi]
Set<String> unique = fruits.stream().collect(Collectors.toSet());
Map<String, Integer> lengths = fruits.stream()
.distinct()
.collect(Collectors.toMap(f -> f, String::length));
String joined = fruits.stream().distinct().collect(Collectors.joining(", "));
System.out.println(unique.size()); // 4
System.out.println(lengths.get("apple")); // 5
System.out.println(joined); // pear, apple, fig, kiwi
}
}Why Streams Are Lazy
Lazy means a step runs only when a later step needs its output. Elements move through the pipeline one at a time. findFirst stops as soon as it has an answer, so the rest of the elements are never processed.
import java.util.stream.Stream;
public class LazyDemo {
public static void main(String[] args) {
Stream.of("a", "b", "c")
.filter(s -> {
System.out.println("filter " + s);
return true;
})
.findFirst();
// Prints only: filter a
}
}Exercise
What does List.of("b", "a", "b", "c").stream().distinct().sorted().limit(2).collect(Collectors.toList()) return?
Show answer
[a, b]. distinct removes the second "b", sorted gives a, b, c, and limit(2) keeps the first two.
Exercise
Why does findFirst return an Optional instead of a plain value?
Show answer
The stream might be empty, or no element might match. An Optional can be empty, which shows that no result exists without using null.