Retrieving elements from an ArrayList by specifying indexes

Is there a way in Java to get a list of objects from an Arraylist to another ArrayList by simply specifying a start and end index?

+5
source share
2 answers

Yes you can use the method subList:

List<...> list2 = list1.subList(startIndex, endIndex);

This returns an idea of ​​this part of the original list; it does not copy data.
If you want a copy:

List<...> list2 = new ArrayList<...> (list1.subList(startIndex, endIndex));
+11
source
/create an ArrayList object
    ArrayList arrayList = new ArrayList();

    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    arrayList.add("4");
    arrayList.add("5");

    /*
       To get a sub list of Java ArrayList use
       List subList(int startIndex, int endIndex) method.
       This method returns an object of type List containing elements from
       startIndex to endIndex - 1.
    */

    List lst = arrayList.subList(1,3);

    //display elements of sub list.
    System.out.println("Sub list contains : ");
    for(int i=0; i< lst.size() ; i++)
      System.out.println(lst.get(i));
0
source

All Articles