AI Hints
Home›Java Tutorial›Streams, filter, map and collect, More Stream Operations
Java · Lesson 105 of 120

More Stream Operations

Sort, count, group.

⏱ 2 min read▶ Video at 2:14:11🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Streams have many more steps. Sorting, limiting, averaging, checking, and grouping. Let's try the most useful ones, on our menu.

  • Sort and limit
  • Average and check
  • Group

More operations

Map to double, then average, gives the average price. Any match asks, is any item over three pounds? Sorted, with a comparator, then limit two, gives the two cheapest. And grouping by, with counting, counts the items of each type. Run it. The average is two sixty seven and a half. Yes, one is over three. The cheapest are tea, and muffin. And there are two drinks, and two foods.

Main.javajava
import java.util.*;
import java.util.stream.*;
public class Main {
    record Product(String name, String type, double price) {}
    public static void main(String[] args) {
        List<Product> menu = List.of(
            new Product("Latte", "drink", 3.20), new Product("Muffin", "food", 2.50),
            new Product("Tea", "drink", 2.10), new Product("Bagel", "food", 2.90));
        double avg = menu.stream().mapToDouble(Product::price).average().getAsDouble();
        System.out.println(avg);
        System.out.println(menu.stream().anyMatch(p -> p.price() > 3));
        System.out.println(menu.stream().sorted(Comparator.comparing(Product::price))
                               .map(Product::name).limit(2).toList());
        Map<String, Long> byType = menu.stream()
            .collect(Collectors.groupingBy(Product::type, Collectors.counting()));
        System.out.println(byType);
    }
}
Output
2.675
true
[Tea, Muffin]
{food=2, drink=2}

Stream cheat sheet

Here are the steps worth remembering. Middle steps return a new stream. Final steps give a result.

StepKindDoes
filter, map, sorted, limitmiddleshape the stream
count, sum, averagefinala number
anyMatch, allMatchfinaltrue or false
toList, collectfinala collection
groupingBycollectora map of groups

Summary

Streams can sort, limit, average, check, and group. Middle steps build the pipeline, and a final step runs it. Next, Optional, a safe box for values that might be missing.

Key takeaways
  • sorted, limit
  • average, anyMatch
  • groupingBy
Next up: Optional — maybe a value