流过滤器(谓词谓词)返回一个由与此给定谓词匹配的流元素组成的流。这是一个中间操作。这些操作总是很懒惰,即执行诸如filter()之类的中间操作实际上并不执行任何过滤,而是创建一个新的流,该新流在遍历时将包含与给定谓词匹配的初始流的元素。
用法:
Stream<T> filter(Predicate<? super T> predicate) Where, Stream is an interface and T is the type of the input to the predicate. The function returns the new stream.
示例1:filter()方法,用于滤除可被5整除的元素。
// Java code for Stream filter
// (Predicate predicate) to get a stream
// consisting of the elements of this
// stream that match the given predicate.
import java.util.*;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a list of Integers
List<Integer> list = Arrays.asList(3, 4, 6, 12, 20);
// Using Stream filter(Predicate predicate)
// to get a stream consisting of the
// elements that are divisible by 5
list.stream().filter(num -> num % 5 == 0).forEach(System.out::println);
}
}
输出:
20
示例2:filter()方法,用于过滤索引为1的具有upperCase字母的元素。
// Java code for Stream filter
// (Predicate predicate) to get a stream
// consisting of the elements of this
// stream that match the given predicate.
import java.util.stream.Stream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a Stream of Strings
Stream<String> stream = Stream.of("Geeks", "fOr",
"GEEKSQUIZ", "GeeksforGeeks");
// Using Stream filter(Predicate predicate)
// to get a stream consisting of the
// elements having UpperCase Character
// at index 1
stream.filter(str -> Character.isUpperCase(str.charAt(1)))
.forEach(System.out::println);
}
}
输出:
fOr GEEKSQUIZ
示例3:filter()方法,用于过滤出以s结尾的元素。
// Java code for Stream filter
// (Predicate predicate) to get a stream
// consisting of the elements of this
// stream that match the given predicate.
import java.util.stream.Stream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a Stream of Strings
Stream<String> stream = Stream.of("Geeks", "foR",
"GeEksQuiz", "GeeksforGeeks");
// Using Stream filter(Predicate predicate)
// to get a stream consisting of the
// elements ending with s
stream.filter(str -> str.endsWith("s"))
.forEach(System.out::println);
}
}
输出:
Geeks GeeksforGeeks
相关用法
- Java LongStream filter()用法及代码示例
- Java IntStream filter()用法及代码示例
- Java DoubleStream filter()用法及代码示例
- Java Optional filter()用法及代码示例
- Java Stream map()用法及代码示例
- Java Stream empty()用法及代码示例
- Java Stream builder()用法及代码示例
- Java Stream toArray()用法及代码示例
- Java Stream peek()用法及代码示例
- Java Stream mapToInt()用法及代码示例
- Java Stream mapToLong()用法及代码示例
- Java Stream mapToDouble()用法及代码示例
- Java Stream.reduce()用法及代码示例
注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 Stream filter() in Java with examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。