Common methods in Stream _limit (delay method)

Take the first few: limit:
Common methods in Stream _limit: The
limit method used to intercept elements in the stream can intercept the stream, and only take the first n. Method signature:

 Stream<T> limit(long maxSize);

The parameter is a long type. If the current length of the collection is greater than the parameter, it will be intercepted; otherwise, no operation will be performed.
The Limit method is a delayed method , it just intercepts the elements in the stream, and returns a new stream, so you can continue to call other methods in the Stream stream

Example:

public class Demo06Stream_limit {
    
    
    public static void main(String[] args) {
    
    
        //获取一个流
        String[] arr = {
    
    "喜羊羊","美羊羊","灰太狼","懒羊羊","红太狼"};
        Stream<String> stream = Stream.of(arr);
        //使用limit对Stream流中的元素进行截取,只要前三个元素
        Stream<String> stream2 = stream.limit(3);
        //遍历stream2流
        stream2.forEach(name-> System.out.println(name));
    }
}

Program demonstration:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44664432/article/details/109155277