Java
Stream layer
Set up data processing with Stream and lambda.
Find large orders with a Stream
We'll add a largeOrders method to OrderBook. This method gathers orders with amount 100 or more into a new list using the chain orders.stream().filter(o -> o.amount >= 100).collect(Collectors.toList()).
filter expects a Predicate; the lambda o -> o.amount >= 100 tests each order. The terminal collect(Collectors.toList()) returns the matching orders as a new List<Order>. The original list is unchanged.
collect(Collectors.toList())
The collect(Collectors.toList()) terminal op gathers matching stream elements into a new List. The result is a mutable list; the stream source is unaffected. Since Java 16 the .toList() shortcut also exists.
The largeOrders method returns a List<Order>; you can run further operations on this list. For example book.largeOrders().size() gives the count of large orders. Each call produces a new list.
Exercise Add the largeOrders method
Add a largeOrders method to the OrderBook class: List<Order> largeOrders() { return orders.stream().filter(o -> o.amount >= 100).collect(Collectors.toList()); }. In main, create an OrderBook book = new OrderBook();, add three orders: "1", "Ayşe", 50, "2", "Alex", 150, "3", "Mehmet", 200. Print the count of large orders with System.out.println(book.largeOrders().size());.
Show example solution
class Order {
String id;
String customer;
int amount;
Order(String id, String customer, int amount) {
this.id = id;
this.customer = customer;
this.amount = amount;
}
}
class OrderBook {
List<Order> orders = new ArrayList<>();
void add(Order o) { orders.add(o); }
void listAll() {
orders.forEach(o -> System.out.println(o.id + " " + o.customer + " " + o.amount));
}
List<Order> largeOrders() {
return orders.stream().filter(o -> o.amount >= 100).collect(Collectors.toList());
}
}
public class Main {
public static void main(String[] args) {
OrderBook book = new OrderBook();
book.add(new Order("1", "Ayşe", 50));
book.add(new Order("2", "Alex", 150));
book.add(new Order("3", "Mehmet", 200));
System.out.println(book.largeOrders().size());
}
}
Test yourself
-
What does filter expect in the largeOrders method?
- Runnable
- Consumer
- Function
- Predicate
Show answer
Predicate — filter expects a Predicate<Order> that returns boolean.
-
Complete the filter lambda
orders.stream().filter(____ -> o.amount >= 100)
Show answer
orders.stream().filter(o -> o.amount >= 100)
-
Match the Stream chain parts
- stream()
- Starts the stream
- filter(...)
- Keeps matches
- collect(...)
- Gathers a List
- Collectors.toList()
- Produces a List
Next lesson: File I/O