How to use subList ()

I have a JSF page that displays a list of Glassfish log files. I use lazy loading for pagination. I save a list of log file names in a Java List .

 private List<directoryListObj> dataList = new ArrayList<>(); dataList = dataList.subList(firstRow, lastRow); 

And here is the problem. For example, I have 35 files in a directory. When i do it

 dataList = dataList.subList(5, 15); 

It works great. But when I do this:

 dataList = dataList.subList(30, 38); 

I get the wrong error index because I want to get the index outside the list. How can I, for example, return list items from 30 to 35? I want if I want to get an index from 30 to 40, but if there are only 35 indexes, to get only 5.

+53
java
Aug 23 2018-12-12T00:
source share
3 answers

Using subList(30, 38); will fail because max index 38 is not available in the list, so it is not possible.

Before requesting a sublist, only the path is possible, you explicitly determine the maximum index using the list () method.

for example, check the size that returns 35, so call sublist(30, size());

OR

COPIED FROM pb2q comment

 dataList = dataList.subList(30, 38 > dataList.size() ? dataList.size() : 38); 
+58
Aug 23 2018-12-12T00:
source share

To get the last item, just use the size of the list as the second parameter. For example, if you have 35 files and you want the last five, you would do:

 dataList.subList(30, 35); 

Guaranteed safe way to do this:

 dataList.subList(Math.max(0, first), Math.min(dataList.size(), last) ); 
+37
Aug 23 2018-12-12T00:
source share

I implemented and tested this; it should cover most bases:

 public static <T> List<T> safeSubList(List<T> list, int fromIndex, int toIndex) { int size = list.size(); if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) { return Collections.emptyList(); } fromIndex = Math.max(0, fromIndex); toIndex = Math.min(size, toIndex); return list.subList(fromIndex, toIndex); } 
+25
Jun 23 '15 at 12:57
source share



All Articles