Java Stream Intermediate Operations

Java Stream Intermediate Operations

Intermediate operations are methods that take an input stream and produce a new output stream, which can then be used for further processing. We will cover some of the most commonly used intermediate operations such as filter, map, sorted, and distinct.

Let's first create a sample list of integers that we will use throughout this tutorial:

List<Integer> numbers = Arrays.asList(5, 2, 9, 1, 6, 3);        

Filtering Elements with filter()

The filter method takes a Predicate as its argument and returns a stream consisting only of elements that match the given predicate. For example, if we want to get all even numbers from our list, we can do it like this:

Stream<Integer> evenNumbers = numbers.stream().filter(n -> n % 2 == 0);
evenNumbers.forEach(System.out::println); // prints "2", "6"        

In this example, we created a new stream called evenNumbers containing only those elements from the original list where the remainder when divided by two is zero (i.e., even numbers). Then, we printed out these values using the forEach method.

Transforming Elements with map()

The map method applies a function to every element in the input stream and produces a new stream consisting of the results. This allows us to perform complex transformations on our data easily. Let's say we want to convert our list of integers into their squares:

Stream<Integer> squareNumbers = numbers.stream().map(n -> n * n);
squareNumbers.forEach(System.out::println); // prints "25", "4", "81", "1", "36", "9"        

Here, we applied the multiplication operator (*) to each element in the stream to compute its square. The resulting stream contains the squared values instead of the original ones.

Sorting Elements with sorted()

The sorted method sorts the elements in ascending order by default or according to a custom Comparator provided as an argument. Note that sorting is not performed until you start iterating over the stream. Here's how we can sort our list of integers:

numbers.stream().sorted().forEach(System.out::println); // prints "1", "2", "3", "5", "6", "9"        

If we wanted to sort the elements in descending order, we could pass a custom comparator like so:

numbers.stream().sorted((a, b) -> Integer.compare(b, a)).forEach(System.out::println); // prints "9", "6", "5", "3", "2", "1"        

This time, we passed a lambda expression implementing the Comparator interface, which compares two integers and returns -1, 0, or 1 depending on whether the first integer is less than, equal to, or greater than the second one, respectively. By reversing the arguments of the compare method, we achieved descending ordering.

Removing Duplicates with distinct()

The distinct method removes any duplicate elements from the stream based on the equals() method. If no duplicates exist, calling distinct has no effect. Here's an example:

List<String> words = Arrays.asList("hello", "world", "hello", "again");
Stream<String> uniqueWords = words.stream().distinct();
uniqueWords.forEach(System.out::println); // prints "hello", "world", "again"        

In this case, since there were multiple occurrences of the word "hello," applying the distinct method reduced them down to just one instance.

Intermediate operations provide powerful ways to manipulate data flowing through Java streams. They allow developers to filter, transform, sort, and remove duplicates efficiently without modifying the underlying collection directly.

Thank you for reading. See you on the next tutorial!





要查看或添加评论,请登录

Arjun Araneta的更多文章

社区洞察

其他会员也浏览了