If you are unfamiliar with Java 8 Streams then I suggest you first check out our Introduction to Streams before reading this article.
Java 8 Filters are an Intermediate Operation that can be performed on a Stream. Traditionally if you had a collection of data such as a List and you wanted to filter out some data, you would need to think either think about the repercussions of mutating the data or simply make a copy of the collection. With Java 8 Filters you are working with Streams so you never end up mutating the original data.
Let’s say you have a list of names and you want to Filter out any names that start with the letter A
.
Given the following ArrayList of Strings
1 2 3 4 5 | List<String> strings = new ArrayList<String>(); strings.add("Alice"); strings.add("Arianna"); strings.add("Jennifer"); strings.add("Melissa"); |
You can use the filter
operation
Filter
1 2 3 | strings.stream() .filter(e -> !e.startsWith("A")) .forEach(System.out::println); |
Which produces the following output to the console:
Console Output
1 2 | Jennifer Melissa |
Let’s say you want to also filter any names that start with M
. You could either chain another filter
Operation or you add the check to your existing filter. Let’s take a look at both.
Add to the existing Filter
1 2 3 | strings.stream() .filter(e -> !e.startsWith("A") && !e.startsWith("M")) .forEach(System.out::println); |
or
Chain New Filter
1 2 3 4 | strings.stream() .filter(e -> !e.startsWith("A")) .filter(e -> !e.startsWith("M")) .forEach(System.out::println); |
Both Operations produce the same result:
Console Output
1 | Jennifer |