當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java LongStream filter()用法及代碼示例


LongStream filter(LongPredicate predicate)返回包含與給定謂詞匹配的該流元素的流。這是一個中間操作。這些操作總是很懶惰,即執行諸如filter()之類的中間操作實際上並不執行任何過濾,而是創建一個新的流,該新流在遍曆時將包含與給定謂詞匹配的初始流的元素。

用法:

LongStream filter(LongPredicate predicate)

Where, LongStream is a sequence of primitive long-valued elements.
LongPredicate represents a predicate (boolean-valued function) 
of one long-valued argument and the function returns the new stream.

示例1:LongStream上的filter()方法。


// Java code for LongStream filter 
// (LongPredicate predicate) to get a stream 
// consisting of the elements of this 
// stream that match the given predicate. 
import java.util.*; 
import java.util.stream.LongStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // Creating an LongStream 
        LongStream stream = LongStream.of(3L, 5L, 6L, 8L, 9L); 
  
        // Using LongStream filter(LongPredicate 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:LongStream上的filter()方法。

// Java code for LongStream filter 
// (LongPredicate predicate) to get a stream 
// consisting of the elements of this 
// stream that match the given predicate. 
import java.util.*; 
import java.util.stream.LongStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // Creating an LongStream 
        LongStream stream = LongStream.of(-2L, -1L, 0L, 1L, 2L); 
  
        // Using LongStream filter(LongPredicate 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


相關用法


注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 LongStream filter() in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。