Get SubList from LinkedList in Java


The subList of a LinkedList can be obtained using the java.util.LinkedList.subList(). This method takes two parameters i.e. the start index for the sub-list(inclusive) and the end index for the sub-list(exclusive) from the required LinkedList. If the start index and the end index are the same, then an empty sub-list is returned.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.LinkedList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      LinkedList<String> l = new LinkedList<String>();
      l.add("John");
      l.add("Sara");
      l.add("Susan");
      l.add("Betty");
      l.add("Nathan");
      System.out.println("The LinkedList is: " + l);
      List subl = l.subList(1, 3);
      System.out.println("The SubList is: " + subl);
   }
}

Output

The LinkedList is: [John, Sara, Susan, Betty, Nathan]
The SubList is: [Sara, Susan]

Now let us understand the above program.

The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows −

LinkedList<String> l = new LinkedList<String>();
l.add("John");
l.add("Sara");
l.add("Susan");
l.add("Betty");
l.add("Nathan");
System.out.println("The LinkedList is: " + l);

The LinkedList.subList() method is used to create a sub-list which contains the elements from index 1(inclusive) to 3(exclusive) of the LinkedList. Then the sub-list elements are displayed. A code snippet which demonstrates this is as follows −

List subl = l.subList(1, 3);
System.out.println("The SubList is: " + subl);

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

804 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements