[java] How to use subList()

I have a JSF page which displays list of Glassfish log files. I use lazy loading for pagination. I keep the list of the log files names into Java List.

private List<directoryListObj> dataList = new ArrayList<>();

dataList = dataList.subList(firstRow, lastRow);

And here is the problem. For example I have 35 files into the directory. When I do this

dataList = dataList.subList(5, 15);

It works fine. But when I do this:

dataList = dataList.subList(30, 38);

I get error wrong index because I want to get index outside of the List. How I can for example return List elements from 30 to 35? I want if I want to get index from 30 to 40 but if there only 35 indexes to get only 5.

This question is related to java

The answer is


You could use streams in Java 8. To always get 10 entries at the most, you could do:

dataList.stream().skip(5).limit(10).collect(Collectors.toList());
dataList.stream().skip(30).limit(10).collect(Collectors.toList());

I've implemented and tested this one; 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);
}

To get the last element, simply use the size of the list as the second parameter. So for example, if you have 35 files, and you want the last five, you would do:

dataList.subList(30, 35);

A guaranteed safe way to do this is:

dataList.subList(Math.max(0, first), Math.min(dataList.size(), last) );