Java IntStream filter()示例
IntStream filter(IntPredicate predicate) 返回一个由这个流中符合给定谓词的元素组成的流。这是一个 中间操作。 这些操作总是懒惰的,即执行中间操作如filter()实际上并不执行任何过滤,而是创建一个新的流,当被遍历时,包含初始流中符合给定谓词的元素。
语法:
IntStream filter(IntPredicate predicate)
其中,IntStream是一个原始int值元素的序列。
IntPredicate代表一个谓词(布尔值函数)
的一个int值参数,该函数返回新的流。
例1: IntStream的filter()方法。
// Java code for IntStream filter
// (IntPredicate predicate) to get a stream
// consisting of the elements of this
// stream that match the given predicate.
import java.util.*;
import java.util.stream.IntStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating an IntStream
IntStream stream = IntStream.of(3, 5, 6, 8, 9);
// Using IntStream filter(IntPredicate predicate)
// to get a stream consisting of the
// elements that gives remainder 2 when
// divided by 3
stream.filter(num -> num % 3 == 2)
.forEach(System.out::println);
}
}
输出:
5
8
例2: IntStream的filter()方法。
// Java code for IntStream filter
// (IntPredicate predicate) to get a stream
// consisting of the elements of this
// stream that match the given predicate.
import java.util.*;
import java.util.stream.IntStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating an IntStream
IntStream stream = IntStream.of(-2, -1, 0, 1, 2);
// Using IntStream filter(IntPredicate predicate)
// to get a stream consisting of the
// elements that are greater than 0
stream.filter(num -> num > 0)
.forEach(System.out::println);
}
}
输出:
1
2