/** * @param list can be null * @param fromIndex inclusive * @param endIndex exclusive * @param <T> * @return */ public static <T> List<T> subListSafely(List<T> list, int fromIndex, int endIndex) { if(list == null){ return new ArrayList<>(); } if(fromIndex < 0 || endIndex <= 0){ return new ArrayList<>(); } if (list.size() - 1 < fromIndex) { return new ArrayList<>(); } return list.subList(fromIndex, Math.min(endIndex, list.size())); } }
And the unit test:
@Test public void subListSafely(){ // null list assertArrayEquals(new Object[]{}, MyCollectionUtils.subListSafely(null, 0, 3).toArray()); //empty list assertArrayEquals(new Object[]{}, MyCollectionUtils.subListSafely(new ArrayList<String>(), 0, 3).toArray()); assertArrayEquals(new Object[]{}, MyCollectionUtils.subListSafely(new ArrayList<String>(), 1, 3).toArray()); //non-empty list, increasing fromIndex one by one assertArrayEquals(new Object[]{}, MyCollectionUtils.subListSafely(Arrays.asList("a", "b", "c"), -1, 3).toArray()); assertArrayEquals(new Object[]{"a", "b", "c"}, MyCollectionUtils.subListSafely(Arrays.asList("a", "b", "c"), 0, 3).toArray()); assertArrayEquals(new Object[]{"b", "c"}, MyCollectionUtils.subListSafely(Arrays.asList("a", "b", "c"), 1, 3).toArray()); assertArrayEquals(new Object[]{"c"}, MyCollectionUtils.subListSafely(Arrays.asList("a", "b", "c"), 2, 3).toArray()); assertArrayEquals(new Object[]{}, MyCollectionUtils.subListSafely(Arrays.asList("a", "b", "c"), 3, 3).toArray()); assertArrayEquals(new Object[]{}, MyCollectionUtils.subListSafely(Arrays.asList("a", "b", "c"), 4, 3).toArray()); //non-empty list, decrease endIndex one by one assertArrayEquals(new Object[]{"a", "b", "c"}, MyCollectionUtils.subListSafely(Arrays.asList("a", "b", "c"), 0, 4).toArray()); assertArrayEquals(new Object[]{"a", "b", "c"}, MyCollectionUtils.subListSafely(Arrays.asList("a", "b", "c"), 0, 3).toArray()); assertArrayEquals(new Object[]{"a", "b"}, MyCollectionUtils.subListSafely(Arrays.asList("a", "b", "c"), 0, 2).toArray()); assertArrayEquals(new Object[]{"a"}, MyCollectionUtils.subListSafely(Arrays.asList("a", "b", "c"), 0, 1).toArray()); assertArrayEquals(new Object[]{}, MyCollectionUtils.subListSafely(Arrays.asList("a", "b", "c"), 0, 0).toArray()); assertArrayEquals(new Object[]{}, MyCollectionUtils.subListSafely(Arrays.asList("a", "b", "c"), 0, -1).toArray()); }