To slice a list in Java, you can use the subList
method provided by the Java standard library.
In this example,
numbers
with integer values.subList
method on the list object numbers
to create a new list from index 1 to index 4 (exclusive).subList
method returns a view of the specified range within the original list.import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3, 4, 5));
List<Integer> slicedNumbers = numbers.subList(1, 4);
System.out.println("Sliced list: " + slicedNumbers);
}
}
Sliced list: [2, 3, 4]
In this example,
words
with string values.subList
method on the list object words
to create a new list from index 2 to index 5 (exclusive).subList
method returns a view of the specified range within the original list.import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("apple", "banana", "cherry", "date", "elderberry"));
List<String> slicedWords = words.subList(2, 5);
System.out.println("Sliced list: " + slicedWords);
}
}
Sliced list: [cherry, date, elderberry]
In this tutorial, we learned How to Slice a List in Java language with well detailed examples.