To get a sublist in Java, you can use the subList()
method of the List
interface.
In this example,
myList
with some elements.subList()
method to get a sublist from myList
. This method takes two parameters: the starting index (inclusive) and the ending index (exclusive).subList()
method returns a view of the specified range within the list.import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> myList = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> subList = myList.subList(1, 4);
System.out.println("Sublist: " + subList);
}
}
Sublist: [2, 3, 4]
In this example,
myList
with some elements.subList()
method to get a sublist from myList
by specifying different start and end indices.subList()
method returns the elements within the specified range.import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> myList = Arrays.asList(10, 20, 30, 40, 50, 60);
List<Integer> subList = myList.subList(2, 5);
System.out.println("Sublist: " + subList);
}
}
Sublist: [30, 40, 50]
In this tutorial, we learned How to get Sub List in Java language with well detailed examples.