
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!
- Drop table using Java JDBC Template
- Java - Check if array contains the value
- YAML Parser using Java Jackson Library Example
- Java Jackson ObjectMapper Class with Examples
- Get Client IP address from HTTP Response in Java
- How to Word-Warp Console logs in IntelliJ
- Exception in thread main java.lang.NoClassDefFoundError: package javaClass
- Setting Java_Home Environment variable on Windows Operating System
- Fix: Maven - Failed to execute goal - Compilation failure - Source/Target option 5 is no longer supported. Use 7 or later
- Java SE JDBC Select Statement Example
- How to extract Java Jar/War/Ear files in Linux
- java: unclosed string literal [Error]
- [Solution] Exception in thread main java.util.EmptyStackException
- Read YAML file Java Jackson Library
- What Java version is used for Minecraft 1.18
- [Java] How to throws Exception using Functional Interface and Lambda code
- [Program] How to read three different values using Scanner in Java
- Java 8 Predicate Functional Interface Examples
- Display Era details (AD BC) in Java Date using SimpleDateFormat
- Convert String Date to Date Object in Java
- Struts 2 Hello World Example in Eclipse
- Read a file using Java 8 Stream
- Java - How to set custom thread name?
- IntelliJ: Error: Could not find or load main class, java.lang.ClassNotFoundException
- java: ']' expected error [fixed]
- How to set CSS background-Image Property - CSS
- How to query database table names [MySQL/Oracle/SQL Server] - MySQL
- macOS Ventura XCode Command Line Tools Installation - MacOS
- Graph API error when querying BookingBusinesses - ErrorExceededFindCountLimit, The GetBookingMailboxes request returned too many results - Microsoft
- How to connect Airpods to Macbook Air or Pro? - MacOS
- How to display hidden files in Eclipse (dot prefixed files) - Eclipse
- Android SecurityException: Need BLUETOOTH ADMIN permissicacheNameAndAddresson: Neither user 10123 nor current process has android.permission.BLUETOOTH_ADMIN - Android
- Convert Java Object to YAML using Jackson Library - Java