
通过满足指定谓词的流中的项目组成的流将由流过滤函数返回。这是一个中间级操作。这些操作总是懒惰的,即运行过滤函数或其他中间操作实际上并不过滤任何内容;相反,它生成一个新的流,当遍历时,包括满足提供的谓词的初始流的项目。
语法
Streamfilter(Predicate super T> predicate)
当T是谓词输入的类型,并且stream是一个接口。
返回类型
A new stream.
实施
-
Eliminating items that may be divided into a range of numbers from 0 to 10.
立即学习“Java免费学习笔记(深入)”;
在特定索引处删除以大写字母开头的条目。
删除以特定字母结尾的组件。
Example 1: filter() method with the operation of filtering the elements which are divisible by 5
// Java Program to get a Stream Consisting of the Elements
import java.util.*;
public class Example {
public static void main(String[] args){
List list = Arrays.asList(3, 4, 6, 12, 20);
list.stream()
.filter(num -> num % 5 == 0)
.forEach(System.out::println);
}
}
Output
20
示例2:使用filter()方法过滤索引1处有大写字母的元素
// Java Program to Get Stream Consisting of Elements
import java.util.stream.Stream;
public class Example {
public static void main(String[] args) {
Stream stream = Stream.of("class", "FOR", "QUIZ", "waytoclass");
stream.filter(str -> Character.isUpperCase(str.charAt(1)))
.forEach(System.out::println);
}
}
Output
FOR QUIZ
Example 3: filter() method with the operation of filtering the element ending with customs alphabetically letter
// Java Program to Get a Stream Consisting of Elements
import java.util.stream.Stream;
public class Example {
public static void main(String[] args){
Stream stream = Stream.of("Class", "FOR", "Quiz", "WaytoClass");
stream.filter(str -> str.endsWith("s"))
.forEach(System.out::println);
}
}
Output
Class WaytoClass
Conclusion
改善我们的Java代码功能的一种方法是利用filter()方法。与强制或方法论相反。然而,在使用filter()函数时需要记住一些事情。
例如,将多个过滤器方法链接在一起可能会导致代码运行缓慢。这是因为可能会创建一个满足谓词条件的元素的新流作为中间操作。因此,减少filter()调用次数的关键是将谓词合并成一个句子。











