Display Sub-List of ArrayList in Java


The sub-list of an ArrayList can be obtained using the java.util.ArrayList.subList() method. 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 ArrayList. 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.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      ArrayList aList = new ArrayList();
      aList.add("Apple");
      aList.add("Mango");
      aList.add("Banana");
      aList.add("Melon");
      aList.add("Guava");
      aList.add("Orange");
      aList.add("Grapes");
      aList.add("Peach");
      List sList = aList.subList(2, 6);
      System.out.println("The sub-list elements are: ");
      for (int i = 0; i < sList.size(); i++) {
         System.out.println(sList.get(i));
      }
   }
}

The output of the above program is as follows

The sub-list elements are
Banana
Melon
Guava
Orange

Now let us understand the above program.

The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. A code snippet which demonstrates this is as follows

ArrayList aList = new ArrayList();
aList.add("Apple");
aList.add("Mango");
aList.add("Banana");
aList.add("Melon");
aList.add("Guava");
aList.add("Orange");
aList.add("Grapes");
aList.add("Peach");

The ArrayList.subList() method is used to create a sub-list which contains the elements from index 2(inclusive) to 6(exclusive) of the ArrayList. Then the sub-list elements are displayed using a for loop. A code snippet which demonstrates this is as follows

List sList = aList.subList(2, 6);
System.out.println("The sub-list elements are: ");
for (int i = 0; i < sList.size(); i++) {
   System.out.println(sList.get(i));
}

Updated on: 30-Jul-2019

615 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements