🔍 Exploring the Most Common Stream Methods in Java 21

🔍 Exploring the Most Common Stream Methods in Java 21

If you work with Java, you’ve likely encountered the powerful Stream API. It’s an incredible tool for manipulating collections in a functional and declarative way. With Java 21, it’s a great time to revisit some of the most useful methods and understand their practical applications.

Here’s a breakdown of the most common methods and how they shine:


1. filter(Predicate)

👉 Purpose: Filters elements that meet a given condition. 💡 Example: Select even numbers from a list.

List<Integer> evens = numbers.stream()
                             .filter(n -> n % 2 == 0)
                             .toList();        

2. map(Function)

👉 Purpose: Transforms elements from one type to another. 💡 Example: Convert a list of names to uppercase.

List<String> upperCaseNames = names.stream()
                                   .map(String::toUpperCase)
                                   .toList();        

3. flatMap(Function)

👉 Purpose: Flattens complex data structures. 💡 Example: Combine nested lists into a single list.

List<String> words = nestedLists.stream()
                                .flatMap(List::stream)
                                .toList();        

4. collect(Collector)

👉 Purpose: Collects Stream results into a collection or another format. 💡 Example: Convert a list into a set.

Set<String> uniqueNames = names.stream()
                               .collect(Collectors.toSet());        

5. forEach(Consumer)

👉 Purpose: Applies an action to each element (often used for side effects). 💡 Example: Print all elements.

names.stream().forEach(System.out::println);        

6. reduce(BinaryOperator)

👉 Purpose: Combines elements into a single result. 💡 Example: Sum all numbers in a list.

int sum = numbers.stream()
                 .reduce(0, Integer::sum);        

7. takeWhile and dropWhile (Introduced in Java 9)

👉 Purpose: Processes part of the Stream based on a condition. 💡 Example: Stop processing when numbers exceed a certain value.

List<Integer> lessThanTen = numbers.stream()
                                   .takeWhile(n -> n < 10)
                                   .toList();        

Pro Tip: In Java 21, prefer immutable collectors like toList() or toSet() for simple cases instead of collect, improving readability and performance.

Which of these methods do you use the most? Share your experiences and practical examples in the comments! 🚀

#Java #Programming #Development #Java21 #Streams

To view or add a comment, sign in

More articles by Bruno Silva

Explore content categories