Create max sublists in Java/Kotlin

How can I create a sublist in Java or Kotlin that will return as many items as possible, without throwing an IndexOutOfBoundsException, regardless of the size of the list?

val list: List = arrayListOf(1, 2, 3, 4)

I want to create a sublist from list that will return as many items as possible without throwing an IndexOutOfBoundsException, regardless of the size of the list. For example:

list.subList(0, 3) // -> [1, 2, 3]
list.subList(0, 5) // -> [1, 2, 3, 4]
list.subList(0, 200) // -> [1, 2, 3, 4]
list.clear()
list.subList(0, 3) // -> []

How can I achieve this in Java or Kotlin?

In Kotlin, you can use the subList method with min function to avoid IndexOutOfBoundsException. Here’s an example:

val list: List<Int> = arrayListOf(1, 2, 3, 4)
val subList = list.subList(0, min(3, list.size))

This will return a sublist of list containing the first 3 items if list has at least 3 items, or all items in list if it has fewer than 3 items.

In Java, you can use the subList method with Math.min function to achieve the same result. Here’s an example:

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
List<Integer> subList = list.subList(0, Math.min(3, list.size()));