To slice the first N elements from a list in Java, you can use the subList
method provided by the List interface.
In this example,
numbers
with integer values.subList
method on the list object numbers
to get a view of the first N elements.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));
int n = 3;
List<Integer> slicedNumbers = numbers.subList(0, n);
System.out.println("Sliced list: " + slicedNumbers);
}
}
Sliced list: [1, 2, 3]
In this example,
words
with string values.subList
method on the list object words
to get a view of the first N elements.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"));
int n = 2;
List<String> slicedWords = words.subList(0, n);
System.out.println("Sliced list: " + slicedWords);
}
}
Sliced list: [apple, banana]
In this tutorial, we learned How to Slice First N Elements from a List in Java language with well detailed examples.