Java
Stream layer
Write data processing with advanced Stream and Optional.
Filtering with Stream
In this lesson you will filter high-severity events with stream(). .filter(e -> e.severity > 2) keeps the events that match; .count() returns the count.
long count = log.stream()
.filter(e -> e.severity > 2)
.count();
count is a terminal operation; it consumes the stream and returns a long. This is shorter than counting by hand with a for-each loop. The filtered count is obtained in one line.
Grouping with groupingBy
Collectors.groupingBy groups events by a property and returns a Map. Each type becomes a key; the value is the list of events of that type.
var grouped = log.stream()
.collect(Collectors.groupingBy(e -> e.type));
For example, info, error and warn are different keys, so grouped.size() gives the number of types. collect is a terminal operation.
Exercise Filter and group with Stream
Add a third event (warn 3) to the previous lesson's log list. Compute log.stream().filter(e -> e.severity > 2).count() and print it. Also build log.stream().collect(Collectors.groupingBy(e -> e.type)) into a grouped Map and print grouped.size().
Show example solution
import java.util.ArrayList;
import java.util.stream.Collectors;
class Event {
String type;
int severity;
Event(String type, int severity) {
this.type = type;
this.severity = severity;
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Event> log = new ArrayList<>();
log.add(new Event("info", 1));
log.add(new Event("error", 5));
log.add(new Event("warn", 3));
long count = log.stream().filter(e -> e.severity > 2).count();
var grouped = log.stream().collect(Collectors.groupingBy(e -> e.type));
System.out.println(count);
System.out.println(grouped.size());
}
}
Test yourself
-
Complete the count call
long count = log.stream()
.filter(e -> e.severity > 2)
.____();
Show answer
long count = log.stream()
.filter(e -> e.severity > 2)
.count();
-
What does filter(e -> e.severity > 2).count() return?
- A list
- A Map
- A long number
- A String
Show answer
A long number — answer: A long number. The count terminal returns a long.
-
Match the Stream concepts
- stream()
- Starts the pipeline
- filter
- Selects by condition
- count
- Returns the count
- groupingBy
- Builds a Map
Next lesson: Concurrent layer