To get a sub-list from a List in Java, you can use the subList() method provided by the List interface. The subList() method takes two arguments: the starting index (inclusive) and the ending index (exclusive) of the sub-list.
Here is an example code that demonstrates how to get a sub-list from a List:
import java.util.ArrayList;
import java.util.List;
public class Example {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
// Get sub-list from index 1 (inclusive) to index 4 (exclusive)
List<String> subList = list.subList(1, 4);
System.out.println("Original list: " + list);
System.out.println("Sub-list: " + subList);
}
}
In this example, we create a List with five elements and then use the subList() method to get a sub-list from index 1 to index 4 (exclusive). We then print both the original list and the sub-list to the console.
It is important to note that the sub-list returned by subList() is a view of the original list, meaning that any changes made to the sub-list will be reflected in the original list and vice versa. If you want to create a new list from the sub-list, you can pass the sub-list to the ArrayList constructor like this:
List<String> newList = new ArrayList<>(list.subList(1, 4));
This creates a new ArrayList that contains the elements of the sub-list. Any changes made to this new list will not affect the original list or the sub-list.