Convert List into Paging results using java 8
In this tutorial, we show the list of result in paging concepts. Like page 1 and no. of results 10.
Page 1 has 1-10 results, page 2 has 11-20 results, page 3 has 21-30 results.
Like page 2 and no. of results 20.
Page 2 has 31-40 results, page 3 has 3-30 results.
List<Owner> ownerList = ownerRepo.findAll(); int pageNumber =1, pageSize=5; List<Owner> pagingResult =ownerList.stream() .skip((long) (pageNumber -1) * pageSize) .limit(pageSize) .toList();
Explaination:
In above code, ownerList have list of Owner Objects.
- Convert the list into steam by steam().
- Skip the first results .
- like page 2 and results 5 means skip the 1-5 then start from 6 β 10.
- so we multiple (2-1) * 5 to result is 5 => we get result start from 6.
- limt the pages .
- we got the result so we limit the result to pageSize.
- limit(pageSize).
- Convert the result into list.
Reference
https://www.digitalocean.com/community/tutorials/java-stream-collect-method-examples
https://www.youtube.com/watch?v=J2pxQFmQsN0