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


Java stream.limit()用法及代碼示例


先決條件: Java8中的流
limit(long N)是java.util.stream.Stream對象的方法。此方法以一個(長N)作為參數,並返回大小不超過N的流。如果N的值很大,則limit()在有序並行管道上可能會非常昂貴,因為limit(N)受限於返回遇到順序中的前N個元素,而不僅僅是任何n個元素。

用法:

Stream<T> limit(long N)

Where N is the number of elements the stream should be 
limited to and this function returns new stream as output.

異常:如果N的值為負,則該函數將引發IllegalArgumentException。


下麵是一些示例,可以更好地理解該函數的實現。
示例1:

// Java code to show implementation 
// of limit() function 
import java.util.*; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
  
        // Creating a list of integers 
        List<Integer> list = new ArrayList<Integer>(); 
  
        // adding elements in the list 
        list.add(-2); 
        list.add(0); 
        list.add(2); 
        list.add(4); 
        list.add(6); 
        list.add(8); 
        list.add(10); 
        list.add(12); 
        list.add(14); 
        list.add(16); 
  
        // setting the value of N as 4 
        int limit = 4; 
        int count = 0; 
        Iterator<Integer> it = list.iterator(); 
  
        // Iterating through the list of integers 
        while (it.hasNext()) { 
            it.next(); 
            count++; 
  
            // Check if first four i.e, (equal to N) 
            // integers are iterated. 
            if (count > limit) { 
  
                // If yes then remove all the remaining integers. 
                it.remove(); 
            } 
        } 
  
        System.out.print("New stream of length N"
                         + " after truncation is : "); 
  
        // Displaying new stream of length 
        // N after truncation 
        for (Integer number : list) { 
            System.out.print(number + " "); 
        } 
    } 
}

輸出:

New stream of length N after truncation is : -2 0 2 4 

應用:

// Java code to show the use of limit() function 
import java.util.stream.Stream; 
import java.util.ArrayList; 
import java.util.List; 
 class gfg{ 
       
     // Function to limit the stream upto given range, i.e, 3 
     public static Stream<String> limiting_func(Stream<String> ss, int range){ 
         return ss.limit(range); 
     } 
       
     // Driver code 
     public static void main(String[] args){ 
           
         // list to save stream of strings 
         List<String> arr = new ArrayList<>(); 
           
         arr.add("geeks"); 
         arr.add("for"); 
         arr.add("geeks"); 
         arr.add("computer"); 
         arr.add("science"); 
          
         Stream<String> str = arr.stream(); 
           
         // calling function to limit the stream to range 3 
         Stream<String> lm = limiting_func(str,3); 
         lm.forEach(System.out::println); 
     } 
 }

輸出:

geeks
for
geeks


相關用法


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