Skip to Content

Get Sub List of Java ArrayList Example

  1. /*
  2.   Get Sub List of Java ArrayList Example
  3.   This Java Example shows how to get sub list of java ArrayList using subList
  4.   method by providing start and end index.
  5. */
  6.  
  7. import java.util.ArrayList;
  8. import java.util.List;
  9.  
  10. public class GetSubListOfJavaArrayListExample {
  11.  
  12.   public static void main(String[] args) {
  13.  
  14.     //create an ArrayList object
  15.     ArrayList arrayList = new ArrayList();
  16.    
  17.     //Add elements to Arraylist
  18.     arrayList.add("1");
  19.     arrayList.add("2");
  20.     arrayList.add("3");
  21.     arrayList.add("4");
  22.     arrayList.add("5");
  23.    
  24.     /*
  25.        To get a sub list of Java ArrayList use
  26.        List subList(int startIndex, int endIndex) method.
  27.        This method returns an object of type List containing elements from
  28.        startIndex to endIndex - 1.
  29.     */
  30.    
  31.     List lst = arrayList.subList(1,3);
  32.        
  33.     //display elements of sub list.
  34.     System.out.println("Sub list contains : ");
  35.     for(int i=0; i< lst.size() ; i++)
  36.       System.out.println(lst.get(i));
  37.      
  38.     /*
  39.       Sub List returned by subList method is backed by original Arraylist. So any
  40.       changes made to sub list will also be REFLECTED in the original Arraylist.
  41.     */
  42.     //remove one element from sub list
  43.     Object obj = lst.remove(0);
  44.     System.out.println(obj + " is removed from sub list");
  45.    
  46.     //print original ArrayList
  47.     System.out.println("After removing " + obj + " from sub list, original ArrayList contains : ");
  48.     for(int i=0; i< arrayList.size() ; i++)
  49.       System.out.println(arrayList.get(i));
  50.    
  51.   }
  52.  
  53. }
  54. /*
  55. Output would be
  56. Sub list contains :
  57. 2
  58. 3
  59. 2 is removed from sub list
  60. After removing 2 from sub list original ArrayList contains :
  61. 1
  62. 3
  63. 4
  64. 5
  65. */