Course contentsShow
← Java
Lesson 1531 of 2,87033. Streams API: Terminal OperationsFree lesson

Practical Examples: Finding Extremes in Real Data

Apply min, max, and count to solve real-world problems like finding oldest users, highest prices, and collection sizes.

Practical Examples: Finding Extremes in Real Data

You'll learn how to apply min, max, and count to solve common real-world data problems.

Now that you understand how min, max, and count work individually, let's see them in action with realistic scenarios. These terminal operations shine when you need to extract meaningful insights from collections of data.

Finding the Oldest User

Imagine you have a User class with an age field. Finding the oldest user is straightforward:

List<User> users = Arrays.asList(
    new User("Alice", 28),
    new User("Bob", 35),
    new User("Carol", 42)
);

Optional<User> oldest = users.stream()
    .max(Comparator.comparingInt(User::getAge));

oldest.ifPresent(u -> 
    System.out.println("Oldest: " + u.getName() + ", age " + u.getAge())
);
// Output: Oldest: Carol, age 42

Finding the Highest Price

For a Product with a price field:

List<Product> products = getProducts();

Optional<Product> mostExpensive = products.stream()
    .max(Comparator.comparingDouble(Product::getPrice));

mostExpensive.ifPresent(p -> 
    System.out.println("Highest price: $" + p.getPrice())
);

Counting Filtered Results

Need to know how many premium users you have?

long premiumCount = users.stream()
    .filter(u -> u.isPremium())
    .count();

System.out.println("Premium users: " + premiumCount);

Combining Operations

You can filter before finding extremes:

Optional<Product> cheapestInStock = products.stream()
    .filter(Product::isInStock)
    .min(Comparator.comparingDouble(Product::getPrice));

Key Takeaway: Use max with comparingInt/Double for highest values, min for lowest, and count after filtering to measure subset sizes—these patterns solve most real-world "find the extreme" problems efficiently.