How to retrieve the first n elements of a list in Java?

To obtain the first n elements of a List, you can use the subList method of the List. This method takes two parameters, the starting index (inclusive) and the ending index (exclusive).

Here is an example code demonstrating how to retrieve the first n elements of a List.

import java.util.ArrayList;
import java.util.List;

public class Main {
    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");

        int n = 3; // 前n个元素

        List<String> subList = list.subList(0, n);
        System.out.println(subList);
    }
}

The output is: [A, B, C]

In the example above, we first created a List and added some elements. Then, we used the subList method to retrieve the first n elements starting from index 0 (inclusive) to index n (exclusive). Finally, we printed out the obtained sublist.

Please note that if n is greater than the size of the List, the subList method will throw an IndexOutOfBoundsException. Make sure the index range is valid when using the subList method.

bannerAds