
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
Have Questions? Post them here!
- Create a Zip file using Java Code programmatically
- Eclipse : A java Runtime Environment (JRE) or Java Development kit (JDK) must be available
- How to Sort a LinkedList in Java
- Loading class com.mysql.jdbc.Driver. This is deprecated. The new driver class is com.mysql.cj.jdbc.Driver
- How to declare and initialize Array in Java Programming
- [Fix] java: integer number too large compilation error
- Java JDBC Connection with MySQL Driver in VS Code + Troubleshooting
- Reading .xls and .xlsx Excel file using Apache POI Java Library
- IntelliJ: Error: Could not find or load main class, java.lang.ClassNotFoundException
- How to get Client IP address using Java Code Example
- Truncate table using Java JDBC Example
- Struts 2 : There is no Action mapped for namespace [/] and action name [form] associated with context path [/proj]
- How to get file path in Idea IntelliJ IDE
- Java Generics explained with simple definition and examples
- Java SE 8 Update 301 available with various bug fixes and security improvements
- Java: Collect Stream as ArrayList or LinkedList
- Java JDBC Connection with PostgreSQL Driver Example
- How to check if Java main thread is alive
- How to fix Java nio NoSuchFileException wile reading a file
- Java 8+ get Day of the Week Examples with LocalDateTime, DateTime, ZonalDateTime and Instant classes
- Ways to Convert Integer or int to Long in Java
- [Java] How to throws Exception using Functional Interface and Lambda code
- [Fix] Spring Boot: mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
- Java: The value of the local variable string is not used
- Java JDBC: Insert Java 8 LocalDate and Time using PreparedStatement
- Fix error The tool was unable to install the Web Server (IIS) Role during SharePoint 2019 Setup - SharePoint
- How to Add a horizontal line in Android Layout - Android
- Compare Current and Previous Versions of Same File (Local History) in Eclipse - Eclipse
- Hide Keyboard Text Input Icon on macOS Ventura Menu Bar - MacOS
- Failed to find provider info for com.facebook.katana.provider.PlatformProvider - Android
- How to install maven in macOS using Terminal Command - MacOS
- How to change Android Button Color using xml attribute and programatically using java - Android
- Top 3 Awesome Text Editors developers prefer at workplace - Sublime