IntStream filter(IntPredicate predicate)返回一個由與給定謂詞匹配的流元素組成的流。這是一個中間操作。這些操作總是很懶惰,即執行諸如filter()之類的中間操作實際上並不執行任何過濾,而是創建一個新的流,該新流在遍曆時將包含與給定謂詞匹配的初始流的元素。
用法:
IntStream filter(IntPredicate predicate) Where, IntStream is a sequence of primitive int-valued elements. IntPredicate represents a predicate (boolean-valued function) of one int-valued argument and the function returns the new stream.
示例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
相關用法
- Java IntStream min()用法及代碼示例
- Java IntStream max()用法及代碼示例
- Java IntStream empty()用法及代碼示例
- Java IntStream count()用法及代碼示例
- Java IntStream peek()用法及代碼示例
- Java IntStream distinct()用法及代碼示例
- Java IntStream average()用法及代碼示例
- Java IntStream noneMatch()用法及代碼示例
- Java IntStream toArray()用法及代碼示例
- Java IntStream anyMatch()用法及代碼示例
- Java IntStream allMatch()用法及代碼示例
- Java IntStream codePoints()用法及代碼示例
- Java IntStream reduce(IntBinaryOperator op)用法及代碼示例
- Java IntStream.Builder build()用法及代碼示例
- Java IntStream reduce(int identity, IntBinaryOperator op)用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 IntStream filter() in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。