Friday, 28 June 2019

Java 8: Stream skip() and limit() method

Java 8 provides streams and many useful methods with it. In this article, I will show the usage of skip and limit methods for pagination.

For the examples below, we can consider data as,
List<String> listOfString = Arrays.asList("A", "B", "C", "D", "E", "F");

1. skip()

List<String> skippedList = listOfString.stream().skip(2).collect(Collectors.toList());
System.out.println("Skipped list: " + skippedList);

2. limit()
List<String> skippedAndLimitedList = listOfString.stream().skip(1).limit(2).collect(Collectors.toList());
System.out.println("Skipped and limi list: " + skippedAndLimitedList);

We can use these methods for implementing pagination on bigger collections.

private static List<String> getPage(final int page, final int size, final List<String> listOfString) {
return listOfString.stream().skip((page - 1) * size).limit(size).collect(Collectors.toList());
}

System.out.println("Page 1 of size 2: " + getPage(1, 2, listOfString));
Output:
Page 1 of size 2: [A, B]

System.out.println("Page 2 of size 2: " + getPage(2, 2, listOfString));
Output:
Page 2 of size 2: [C, D]

System.out.println("Page 1 of size 100: " + getPage(1, 100, listOfString));
Output:
Page 1 of size 100: [A, B, C, D, E, F]