Just Learn Code

Streamline Your Java Collections with Stream and Filter()

Stream and Filter() Method: A Comprehensive Guide

Have you ever felt burdened by a lengthy code that requires frequent iterations to manipulate data? If you’re familiar with Java programming, you’re probably aware of the for-loop construct and the tons of code you have to write to perform basic operations like filtering and transforming collections of data.

Luckily for us, Java introduced Stream API a powerful, concise, and elegant way to perform common operations with Java collections.

Definition of Stream API

Stream API is a modern Java tool that provides declarative functions to process data in a collection. It allows you to operate on the elements of a collection using functions like filter() and map(), which simplifies your code while also speeding it up.

The most important thing to remember about Stream API is that it’s immutable, which means that each operation returns a new Stream.

Definition and Working of Filter() Method

The filter() method is one of the most frequently used methods in Stream API. It helps to isolate elements in a collection based on certain criteria.

The filter() method is also called a “predicate,” which is a fancy way of saying that it’s a function that takes an input and returns a Boolean value. Here’s how filter() works in practice.

Let’s say you have a list of integers:

“`

List nums = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

“`

Now, let’s use filter() to get even numbers from this list:

“`

List evenNums = nums.stream()

.filter(n -> n % 2 == 0)

.collect(Collectors.toList());

“`

In the example above, we filter out all numbers that are not even using a lambda expression. The lambda expression is passed to the filter() method, which returns a Stream of even numbers.

Since we need to collect the filtered data into a List, we use the collect() method, which we’ll discuss shortly.

Stream With Filter() and Collect() Methods in Java

Definition and Working of Collect() Method

The collect() method is a terminal operation that allows you to convert a Stream into another type. It can be used to collect the filtered data into a new collection.

The collect() method is also called a “reduction operation,” which is a fancy way of saying that it combines all elements of a stream into a single object. Let’s stick with our example above and use the collect() method to form a new List:

“`

List evenNums = nums.stream()

.filter(n -> n % 2 == 0)

.collect(Collectors.toList());

“`

In the example above, the collect() method receives the Stream and returns a new List containing the filtered data.

Example: Filtering a List of Students’ Names

Let’s take the above example and apply it to a real-world use case. Suppose we have a List of students’ names:

“`

List students = Arrays.asList(“Mike”, “John”, “Doe”, “Gary”, “Sarah”, “Jane”);

“`

Our goal is to filter out students named “Doe” and collect students’ names that contain the letter “a.”

“`

List filteredNames = students.stream()

.filter(s -> !s.equals(“Doe”))

.filter(s -> s.contains(“a”))

.collect(Collectors.toList());

“`

In the example above, we’ve used two filter operations one filter() operation removes the name “Doe” from the Stream, and the other filter() operation accepts only names with the letter “a.” The collect() method collects the filtered names into a new List.

Conclusion

In conclusion, Stream API is a powerful tool that provides an elegant way to handle large collections of data. With Stream API, you use filter() to isolate elements based on certain criteria and collect() to convert the Stream into another type of collection.

These methods simplify coding while also improving efficiency and readability. Implement Stream API in your future Java programming to optimize your code!

Stream with Filter() and ForEach() Method in Java

As we discussed in our previous article, Stream API is a modern Java tool that provides declarative functions to process data in a collection. One of the most frequently used methods in Stream API is filter(), which isolates elements based on certain criteria.

In this article, we will discuss another important method called forEach(), which prints the elements of a Stream, one at a time.

Definition and Working of ForEach() Method

The forEach() method is a terminal operation that performs an operation on each element of a Stream. The operation can be anything, like printing the element to the console or calling a function on it.

It’s important to remember that the forEach() method is a terminal operation, which means that it ends the stream and provides us with the final output. Here’s an example:

“`

List nums = Arrays.asList(1, 2, 3, 4, 5);

nums.stream()

.filter(n -> n % 2 == 0)

.forEach(System.out::println);

“`

In the example above, we have a List of integers, and we’re calling stream() on it to get a Stream.

We’re then using filter() to get even numbers. Finally, we’re using forEach() to print each even number to the console, one at a time.

The output would be:

“`

2

4

“`

Example: Printing Numbers Divisible by Five

Now, let’s take an example where we need to print numbers that are divisible by five:

“`

List nums = Arrays.asList(10, 15, 20, 25, 30);

nums.stream()

.filter(n -> n % 5 == 0)

.forEach(System.out::println);

“`

In the example above, we’ve used the filter() method to get the numbers that are divisible by five. The forEach() method is then used to print each of these numbers to the console.

The output would be:

“`

10

15

20

25

30

“`

Stream with Filter() and Multiple Conditions in Java

So far, we’ve seen examples where we’re using filter() with a single condition to filter out elements from a Stream. But what if we want to filter elements based on multiple conditions?

Let’s explore how we can use logical operators to pass multiple conditions to the filter() method.

Using Logical Operators to Pass Multiple Conditions to Filter()

Suppose we have a list of integers, and we want to filter out numbers that are divisible by five and greater than ten:

“`

List nums = Arrays.asList(2, 5, 10, 15, 20, 25);

nums.stream()

.filter(n -> n % 5 == 0 && n > 10)

.forEach(System.out::println);

“`

The output would be:

“`

15

20

25

“`

In the example above, we’ve used the logical AND operator (&&) to pass two conditions to the filter() method. The first condition checks if the number is divisible by 5, and the second condition checks if the number is greater than 10.

Only those numbers that satisfy both conditions are returned by the filter() method. We can also use other logical operators like OR (||) and NOT (!) to pass multiple conditions to the filter() method.

Here’s an example:

“`

List nums = Arrays.asList(2, 5, 10, 15, 20, 25);

nums.stream()

.filter(n -> (n % 2 == 0 || n % 5 == 0) && n > 10)

.forEach(System.out::println);

“`

In the example above, we’ve used both OR (||) and AND (&&) operators to pass multiple conditions to the filter() method. The first condition checks if the number is divisible by 2 or 5, and the second condition checks if the number is greater than 10.

Conclusion

Stream API provides a concise, elegant, and efficient way to process data in Java collections. The filter() method allows us to isolate elements based on certain criteria, while the forEach() method performs an operation on each element of a Stream.

We can also use logical operators to pass multiple conditions to the filter() method and filter out elements that satisfy those conditions. Now that you’re familiar with these essential Stream API methods, take advantage of them to make your Java programming more efficient and elegant.

Stream with Filter() and Map() Method in Java

In our previous articles, we discussed how Stream API provides an elegant way to process data in Java collections using methods like filter() and forEach(). In this article, we’ll explore another important method called map(), which allows you to transform the elements of a Stream.

Definition and Working of Map() Method

The map() method is an intermediate operation that creates a new Stream by applying a function to each element in the original Stream. The function takes an input and returns a new output, which is then collected into the new Stream.

It’s important to remember that the map() method returns a Stream of the same size as the original Stream. Here’s an example:

“`

List nums = Arrays.asList(1, 2, 3, 4, 5);

nums.stream()

.filter(n -> n % 2 == 0)

.map(n -> n * n)

.forEach(System.out::println);

“`

In the example above, we have a List of integers, and we’re calling stream() on it to get a Stream.

We’re then using filter() to get even numbers. Finally, we’re using map() to square each even number, which creates a new Stream of the same size.

The forEach() method is then used to print each squared number to the console. The output would be:

“`

4

16

“`

Example: Squaring Elements Divisible by Five

Now, let’s take an example where we need to square numbers that are divisible by five:

“`

List nums = Arrays.asList(10, 15, 20, 25, 30);

nums.stream()

.filter(n -> n % 5 == 0)

.map(n -> n * n)

.forEach(System.out::println);

“`

In the example above, we’ve used the filter() method to get the numbers that are divisible by five. The map() method is then used to square each of these numbers, creating a new Stream of squared numbers.

The forEach() method is then used to print each squared number to the console. The output would be:

“`

100

225

400

625

900

“`

Stream with Stacking Several Filter() Methods in Java

So far, we’ve seen examples where we’re using filter() with a single condition to filter out elements from a Stream. But what if we want to apply multiple conditions to filter out elements?

Let’s see how we can use the filter() method to apply multiple conditions.

Stacking Filter() Method to Apply Multiple Conditions

Let’s say we have a list of strings, and we want to filter out strings that have a length greater than three and contain the substring “

stack”:

“`

List words = Arrays.asList(“

stack”, “overflow”, “java”, “programming”);

words.stream()

.filter(w -> w.length() > 3 && w.contains(“

stack”))

.forEach(System.out::println);

“`

The output would be:

“`

stack

“`

In the example above, we’ve used the logical AND operator (&&) to pass two conditions to the filter() method. The first condition checks if the length of the string is greater than 3, and the second condition checks if the string contains the substring “

stack”.

Only those strings that satisfy both conditions are returned by the filter() method. We can also use other logical operators like OR (||) and NOT (!) to pass multiple conditions to the filter() method.

Here’s an example:

“`

List words = Arrays.asList(“

stack”, “overflow”, “java”, “programming”);

words.stream()

.filter(w -> (w.length() < 4 || w.contains("

stack”)) && !w.equals(“java”))

.forEach(System.out::println);

“`

In the example above, we’ve used both OR (||) and NOT (!) operators to pass multiple conditions to the filter() method. The first condition checks if the length of the string is less than 4 or if the string contains the substring “

stack”.

The second condition checks if the string is not equal to “java”.

Conclusion

Stream API provides a powerful set of tools that allow developers to process data in Java collections in an efficient, concise, and elegant way. With the help of methods like filter(), map(), and forEach(), developers can filter, transform and consume data in collections with ease.

Furthermore, they can use different combinations of these methods to apply complex operations on the data. This makes the Stream API an essential tool in modern Java programming.

In this series of articles, we explored Stream API a powerful and modern Java tool that provides declarative functions to process data in collections. We discussed methods like filter(), map(), forEach(), and collect() that help in filtering, transforming, consuming and collecting data in a collection in a concise, elegant and efficient way.

We also showed how

stacking several filter() methods and using logical operators can help in applying multiple conditions for filtering operations. These methods are essential in modern Java programming, as they simplify the code and improve its efficiency and readability.

The takeaway is that by using Stream API, developers can optimize their code, make it more concise and elegant, and ultimately improve their programming skills.

Popular Posts