WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Java Collections Β· Intermediate Β· question 32 of 100

How do you get a sub-list from a List in Java?

πŸ“• Buy this interview preparation book: 100 Java Collections questions & answers β€” PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview β€” then scores it.
πŸ“ž Practice Java Collections β€” free 15 min
πŸ“• Buy this interview preparation book: 100 Java Collections questions & answers β€” PDF + EPUB for $5

All 100 Java Collections questions Β· All topics