Streams is one of the most powerful feature that were added to Java core libraries in the Java 8 version. In this tutorial, we will take a look at various examples to make use of filter() with Streams and related methods to find a solution to a use-case,
Filter method signature:Stream<T> filter(Predicate<? super T> predicate);
Example 1: Use Stream filter to find even and off numbers
In this example, we have made use of filter() with collect() method to collect result as a List.
package org.code2care.java;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class JavaStreamFiltersExamples {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.addAll(Arrays.asList(1,2,3,4,5,6,7,8,9,10));
List<Integer> evenNumbers = numbers.stream().filter(number -> number %2 ==0).collect(Collectors.toList());
List<Integer> oddNumbers = numbers.stream().filter(number -> number %2 !=0).collect(Collectors.toList());
System.out.println("Even Numbers" + evenNumbers);
System.out.println("Odd Numbers" + oddNumbers);
}
}
Output:
Even Numbers[2, 4, 6, 8, 10]
Odd Numbers[1, 3, 5, 7, 9]
Example 2: Use Stream filter to all names starts with letter S
In this example, have make use of filter() with forEach() to print out the results on console,
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.addAll(Arrays.asList("Sam", "Chris", "Mike", "Eric", "Jose", "Samuel", "Scott"));
System.out.println("All Names starting with Letter S in list " + names + " are: ");
names.stream().filter(name -> name.startsWith("S")).forEach(System.out::println);
}
Output:
All Names starting with Letter S in the list [Sam, Chris, Mike, Eric, Jose, Samuel, Scott] are:
Sam
Samuel
Scott
Example 3: Use Stream filter to get the sum of all numbers > 3 in the list
In this example, have made use of filter() to filter out numbers > 3 and them used mapOfInt() and finally sum() to get the sum,
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(5,2,6,8,9,1);
int sum = numbers.stream().filter(number -> number > 3).mapToInt(i -> i).sum();
System.out.println("Sum of numbers > 3 is "+ sum);
}
Output:
Sum of numbers > 3 is 28
Facing issues? Have Questions? Post them here! I am happy to answer!
- Deep Dive into Java 8 Predicate Interface
- Read and Parse XML file using Java DOM Parser [Java Tutorial]
- Java 8 Predicate Functional Interface isEqual() Method Example
- Convert Multidimensional Array toString In Java
- How to read int value using Scanner Class Java
- Spring Boot AI + LLM + Java Code Example
- Write to a File using Java Stream API
- Implementing Bubble Sort Algorithm using Java Program
- How to Fix XmlBeanDefinitionStoreException in Java SpringBoot ApplicationConfig.xml
- YAML Parser using Java Jackson Library Example
- [Fix] java: integer number too large compilation error
- Convert JSON String to Java GSON Object Example
- Read a file using Java 8 Stream
- Java Spring Boot 3 Web Hello World with Gradle in IntelliJ
- Ways Compare Dates in Java Programming with Examples
- Pretty Print JSON String in Java Console Output
- Java JDBC with Join Queries Example
- How to Check For Updates on Windows 11 (Step-by-Step)
- [Fix] java.net.MalformedURLException: unknown protocol
- How to display date and time in GMT Timezone in Java
- Error: LinkageError occurred while loading main class UnsupportedClassVersionError [Eclipse Java]
- How to convert a String to Java 8 Stream of Char?
- RabbitMQ Queue Listener Java Spring Boot Code Example
- 5+ Fibonacci number Series Java Program Examples [ 0 1 1 2 3 ..]
- Handling NullPointerException with Java Predicate
- How to know file encoding in Microsoft Windows Notepad? - Microsoft
- How to make a Python Program Pause for X seconds - Python
- How to Auto Save a file in Notepad++ - NotepadPlusPlus
- How to make EditText text to uppercase or lowercase on macOS - MacOS
- Unsupported major.minor version 52.0 in java - Java
- Python Slicing Working with examples - Python
- Unable to load VM from snapshot. The snapshot has been saved for a different hardware configuration - Android
- How to add hint text in bootstrap input text field and text area - Bootstrap