Java Stream limit()方法
limit(long N)是 java.util.stream. Stream对象的一个方法。limit()在有序的并行管道上可能是相当昂贵的,如果N的值很大,因为limit(N)被限制为返回遇到的顺序中的前N个元素,而不是任何N个元素。
语法:
Stream<T> limit(long N)
其中N是流应限制的元素数,该函数返回新的流作为输出。
异常: 如果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