Java
Stream layer
Set up data flow with advanced Stream and Optional.
Filtering with Stream
In this lesson you will filter with stream(). .filter(t -> t.amount > 100) keeps the records that match the condition; .toList() collects the result into a list.
var filtered = ledger.stream()
.filter(t -> t.amount > 100)
.toList();
filter takes a Predicate; it is applied to each element and only the ones returning true stay. This is shorter than filtering by hand with a for-each loop. The result is again a list; its size comes from filtered.size().
Grouping with groupingBy
Collectors.groupingBy groups elements by a property and returns a Map. Each category becomes a key; the value is the list of records in that category.
var grouped = ledger.stream()
.collect(Collectors.groupingBy(t -> t.category));
For example, market and fuel are different keys, so grouped.size() gives the number of categories. collect is a terminal operation; it consumes the stream and produces a result.
Exercise Filter and group with Stream
Use the previous lesson's ledger list. Build ledger.stream().filter(t -> t.amount > 100).toList() and print filtered.size(). Also build ledger.stream().collect(Collectors.groupingBy(t -> t.category)) into a grouped Map and print grouped.size(). You may use the fully qualified name java.util.stream.Collectors.
Show example solution
import java.util.ArrayList;
class Transaction {
String category;
int amount;
Transaction(String category, int amount) {
this.category = category;
this.amount = amount;
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Transaction> ledger = new ArrayList<>();
ledger.add(new Transaction("market", 120));
ledger.add(new Transaction("fuel", 80));
var filtered = ledger.stream()
.filter(t -> t.amount > 100)
.toList();
var grouped = ledger.stream()
.collect(java.util.stream.Collectors.groupingBy(t -> t.category));
System.out.println(filtered.size());
System.out.println(grouped.size());
}
}
Test yourself
-
Complete the filter call
var filtered = ledger.stream()
.____(t -> t.amount > 100)
.toList();
Show answer
var filtered = ledger.stream()
.filter(t -> t.amount > 100)
.toList();
-
What does groupingBy(t -> t.category) return?
- A list
- A Map by category
- A number
- A filter
Show answer
A Map by category — groupingBy returns a Map; keys are categories, values are lists.
-
Match the Stream concepts
- stream()
- Starts the pipeline
- filter
- Selects by condition
- toList
- Collects into a list
- groupingBy
- Builds a Map
Next lesson: Concurrent layer