import java.util.LinkedList; import java.util.List; public class LinkedListSublistExample { public static void main(String[] args) { // Creating a LinkedList ListlinkedList = new LinkedList (); // Adding elements to the LinkedList linkedList.add("Apple"); linkedList.add("Banana"); linkedList.add("Grapes"); linkedList.add("Orange"); linkedList.add("Mango"); // Getting sublist from index 1 to 3 (exclusive) List sublist = linkedList.subList(1, 3); // Displaying the sublist System.out.println("Sublist: " + sublist); } }
Sublist: [Banana, Grapes]In this example, we have created a LinkedList of strings and added some elements to it. Then we have used the subList() method to get a sublist of elements from index 1 to 3 (excluding element at index 3). The sublist is then printed. This method is located in the java.util package library.