Aguid
Aguid

Reputation: 1043

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
  }
} 

Upvotes: 3

Views: 290

Answers (3)

Ousmane D.
Ousmane D.

Reputation: 56423

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.

Upvotes: 3

Aleksandr
Aleksandr

Reputation: 438

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

Upvotes: 5

Parijat Purohit
Parijat Purohit

Reputation: 921

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.

Upvotes: 2

Related Questions