.subList()
In Java, the .subList()
method is a powerful feature of the List interface that obtains a portion of the list based on specified indices. This method provides a convenient way to create a sublist containing elements from the original list.
Syntax
List<E> subList (int fromIndex, int toIndex)
fromIndex
: The starting index of the sublist.toIndex
: The ending index of the sublist. The element at this index is excluded from the sublist.
Example
Below is an example demonstrating the usage of the .subList()
method:
import java.util.ArrayList;import java.util.List;public class SubListExample {public static void main(String[] args) {// Create an ArrayListArrayList<String> exampleList = new ArrayList<>();// Add elements to the ArrayListexampleList.add("Item A");exampleList.add("Item B");exampleList.add("Item C");exampleList.add("Item D");exampleList.add("Item E");// Use .subList() to obtain a portion of the listList<String> subList = exampleList.subList(1, 4);// Display the original and sublistSystem.out.println("Original List: " + exampleList);System.out.println("SubList (inclusive index 1, exclusive index 4): " + subList);}}
This is the output of the above code:
Original List: [Item A, Item B, Item C, Item D, Item E]SubList(inclusive index 1, exclusive index 4): [Item B, Item C, Item D]
In this example, the original ArrayList
is created with five elements. The .subList(1, 4)
call creates a sublist containing elements from index 1 (inclusive) to index 4 (exclusive). The result is then printed to the console.
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.