Home >Java >javaTutorial >Java Stream API Filter
A stream consisting of items from the stream that satisfy the specified predicate will be returned by the stream filter function. This is an intermediate level operation. These operations are always lazy, i.e. running a filter function or other intermediate operation does not actually filter anything; instead, it generates a new stream that, when traversed, includes items from the initial stream that satisfy the provided predicate.
Stream<T> filter(Predicate<? super T> predicate)
When T is the type of the predicate input, and stream is an interface.
A new stream.
Eliminating items that may be divided into a range of numbers from 0 to 10.
Delete entries starting with an uppercase letter at a specific index.
Remove components ending with specific letters.
// Java Program to get a Stream Consisting of the Elements import java.util.*; public class Example { public static void main(String[] args){ List<Integer> list = Arrays.asList(3, 4, 6, 12, 20); list.stream() .filter(num -> num % 5 == 0) .forEach(System.out::println); } }
20
// Java Program to Get Stream Consisting of Elements import java.util.stream.Stream; public class Example { public static void main(String[] args) { Stream<String> stream = Stream.of("class", "FOR", "QUIZ", "waytoclass"); stream.filter(str -> Character.isUpperCase(str.charAt(1))) .forEach(System.out::println); } }
FOR QUIZ
// Java Program to Get a Stream Consisting of Elements import java.util.stream.Stream; public class Example { public static void main(String[] args){ Stream<String> stream = Stream.of("Class", "FOR", "Quiz", "WaytoClass"); stream.filter(str -> str.endsWith("s")) .forEach(System.out::println); } }
Class WaytoClass
One way to improve the functionality of our Java code is to utilize the filter() method. The opposite of coercion or methodology. However, there are some things to keep in mind when using the filter() function.
For example, chaining multiple filter methods together may cause your code to run slowly. This is because a new stream of elements that satisfy the predicate condition may be created as an intermediate operation. Therefore, the key to reducing the number of filter() calls is to combine the predicates into a single sentence.
The above is the detailed content of Java Stream API Filter. For more information, please follow other related articles on the PHP Chinese website!