简体   繁体   中英

Java8 Stream: Why the method Stream.skip(long n) takes long instead of int as parameter?

Here the definition of the skip method of Stream :

skip(long n) Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream.

My question is why the parameter is long instead of int ?

Here an example :

import java.util.Arrays;
import java.util.List;
public class Main {
  public static void main(String[] args) {
    List<String> stringList = Arrays.asList("1","1","2","3","4");

    stringList.stream()
           .skip(2)
           .forEach(System.out::print);// will prints 234
  }
} 

Because not all lists are limited to Integer.MAX_VALUE amount of elements.
For example LinkedList .

Sometimes you may wish to skip on an infinite stream in which case you may need a number greater than the maximum an int type can hold. Hence it makes complete sense to make such a method accept the largest integer possible. Also, as @Joop Eggen has commented, it's consistent with count() . of course, one can argue then we could just have both count() and skip() return/accept an int but to leverage streams sometimes we may need the type which can hold the largest integer possible.

That is because Stream does not always come from a collection like ArrayList where the maximum length is Integer.MAX_VALUE but can also be created over files for each line, practically making the stream to possibly achieve values larger than int .

More cases like LinkedList also provide you the possibility of going above Integer.MAX_VALUE number of elements in the List .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM