LongStream limit(long maxSize)返回包含此流元素的流,該流的長度被截斷為不超過maxSize。
注意:LongStream limit()是一種短路的有狀態中間操作,即,當使用無限輸入進行處理時,它可能會產生有限的流,而無需處理整個輸入。
用法:
LongStream limit(long maxSize)
參數:
- LongStream : 一係列原始long值元素。這是Stream的長期原始專業化。
- maxSize : 流應限於的元素數。
返回值:該函數返回一個由該流的元素組成的流,其長度被截斷為不超過maxSize。
異常:如果maxSize為負數,該函數將拋出IllegalArgumentException。
示例1:
// Java code for LongStream limit
// (long maxSize)
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, 4L, 6L, 8L, 10L);
// Using LongStream limit(long maxSize) to
// get a stream consisting of the elements of
// this stream, truncated to be no longer
// than maxSize in length.
stream.limit(3).forEach(System.out::println);
}
}
輸出:
2 4 6
示例2:
// Java code for LongStream limit
// (long maxSize)
import java.util.*;
import java.util.stream.LongStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating an LongStream of numbers [5, 6, .. 11]
LongStream stream = LongStream.range(5, 12);
// Using LongStream limit(long maxSize) to
// get a stream consisting of the elements of
// this stream, truncated to be no longer
// than maxSize in length.
stream.limit(4).forEach(System.out::println);
}
}
輸出:
5 6 7 8
示例3:
// Java code for LongStream limit
// (long maxSize)
import java.util.*;
import java.util.stream.LongStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating an LongStream
LongStream stream = LongStream.iterate(4L, num -> num + 2);
// Using LongStream limit(long maxSize) to
// get a stream consisting of the elements of
// this stream, truncated to be no longer
// than maxSize in length.
stream.limit(4).forEach(System.out::println);
}
}
輸出:
4 6 8 10
LongStream limit()和之間的區別長流skip():
- limit()方法返回減少的第一maxSize元素流,但skip()方法在跳過第一maxSize元素之後返回其餘元素流。
- limit()是一種短路的有狀態中間操作,即,當使用無限輸入進行處理時,它可能會生成有限的流,而無需處理整個輸入,但是skip()是有狀態的中間操作,即,可能需要先處理整個輸入產生結果。
相關用法
- Java IntStream limit()用法及代碼示例
- Java LongStream of()用法及代碼示例
- Java LongStream sum()用法及代碼示例
- Java stream.limit()用法及代碼示例
- Java DoubleStream limit()用法及代碼示例
- Java LongStream mapToDouble()用法及代碼示例
- Java LongStream concat()用法及代碼示例
- Java LongStream builder()用法及代碼示例
- Java LongStream iterator()用法及代碼示例
- Java LongStream asDoubleStream()用法及代碼示例
- Java LongStream boxed()用法及代碼示例
- Java LongStream mapToObj()用法及代碼示例
- Java LongStream toArray()用法及代碼示例
- Java LongStream rangeClosed()用法及代碼示例
- Java LongStream range()用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 LongStream limit() in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。