java intfilter_Java IntStream filter()用法及代码示例
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 intfilter_Java IntStream filter()用法及代码示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring什么版本支持java8,与J
- 下一篇: java美元兑换,(Java实现) 美元