Get a sublist of ArrayList in Java
To get a portion of the ArrayList in Java, use the method subList() of the ArrayList.List subList(int fromIndex, int toIndex)
fromIndex is included and toIndex excludes ( [fromIndex, toIndex[ ). This method returns an object of type list so, to store the sublist in another ArrayList, we need to create this ArrayList from List: new ArrayList(input.subList(fromIndex, toIndex)) . On the other hand, if we store the resulting sublist in a List then, there is no problem, as in the example.
import java.util.ArrayList;Runtime:
import java.util.List;
public class ArrayListSublist {
public static void main(String[] args) {
// Create an ArrayList< String>
ArrayList< String> aList = new ArrayList< String> ();
//add strings to ArrayList
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
System.out.println("ArrayList");
for(String e:aList)
System.out.println(e);
List list = aList.subList(1, 4);
System.out.println("ArrayList ");
for(int i=0; i< list.size(); i++)
System.out.println(list.get(i));
}
}
ArrayList
1
2
3
4
5
ArrayList
2
3
4
Remaque:
The subList() method throws the exception IndexOutOfBoundsException if the specified index is less than 0 or exceeds the size.
IllegalArgumentException if the fromIndex is larger than the toIndex, in other wordsfromIndex > toIndex.
The subList() method throws the exception IndexOutOfBoundsException if the specified index is less than 0 or exceeds the size.
IllegalArgumentException if the fromIndex is larger than the toIndex, in other wordsfromIndex > toIndex.