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


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


流過濾器(謂詞謂詞)返回一個由與此給定謂詞匹配的流元素組成的流。這是一個中間操作。這些操作總是很懶惰,即執行諸如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


相關用法


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