Java Program to display sub-list of ArrayList

Java 8Object Oriented ProgrammingProgramming

To display the sub-list of ArrayList, let us first declare an ArrayList and add some elements −

ArrayList<String>arrayList = new ArrayList<String>();
arrayList.add("100");
arrayList.add("200");
arrayList.add("300");
arrayList.add("400");
arrayList.add("500");
arrayList.add("600");
arrayList.add("700");
arrayList.add("800");
arrayList.add("900");
arrayList.add("1000");

Get the sub-list of ArrayList now. Here, we are getting sub-list from array index 4 to 8 −

List<String>list = arrayList.subList(4, 8);

Example

 Live Demo

import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      ArrayList<String>arrayList = new ArrayList<String>();
      arrayList.add("100");
      arrayList.add("200");
      arrayList.add("300");
      arrayList.add("400");
      arrayList.add("500");
      arrayList.add("600");
      arrayList.add("700");
      arrayList.add("800");
      arrayList.add("900");
      arrayList.add("1000");
      System.out.println("ArrayList...");
      for (String s: arrayList)
         System.out.println(s);
      List<String>list = arrayList.subList(4, 8);
      System.out.println("SubList of ArrayList...");
      for (int i = 0; i < list.size(); i++)
         System.out.println(list.get(i));
   }
}

Output

ArrayList...
100
200
300
400
500
600
700
800
900
1000
SubList of ArrayList...
500
600
700
800
raja
Published on 24-Apr-2019 13:55:01
Advertisements