How to use subList()

前端 未结 4 1535
[愿得一人]
[愿得一人] 2020-11-30 07:04

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.

相关标签:
4条回答
  • 2020-11-30 07:37

    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);
    }
    
    0 讨论(0)
  • 2020-11-30 07:39

    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) );
    
    0 讨论(0)
  • 2020-11-30 07:46

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

    Only way may be before asking for the sublist, you explicitly determine the max index using list size() method.

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

    OR

    COPIED FROM pb2q comment

    dataList = dataList.subList(30, 38 > dataList.size() ? dataList.size() : 38);
    
    0 讨论(0)
  • 2020-11-30 07:48

    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());
    
    0 讨论(0)
提交回复
热议问题