To get a sublist of a list in Java, you can use the subList
method of the List
interface. This method takes two arguments: the starting index (inclusive) and the ending index (exclusive) of the sublist, and returns a view of the list that includes the elements between the specified indices.
Here's an example of how to use the subList
method to get a sublist of a List
object:
List<String> list = Arrays.asList("apple", "banana", "cherry", "date", "elderberry"); List<String> sublist = list.subList(1, 4); // sublist is ["banana", "cherry", "date"]
In this example, we're getting a sublist of the list
object that includes the elements at indices 1, 2, and 3 (the second, third, and fourth elements).
Note that the subList
method returns a view of the list, not a new list. This means that any changes made to the sublist will be reflected in the original list.
You can find more information about the subList
method and examples of how to use it in the Java documentation.