Sublist from ArrayList

In this article, we will understand how to get sublist from the existing ArrayList.

We just need to specify the from_Index and to_Index to specify the range of sublist using a method defined in ArrayList as below

  1. List subList(int fromIndex, int toIndex)
List subList(int fromIndex, int toIndex)
Note :
fromIndex is inclusive and toIndex is exclusive The return value of subList method is again another list

Example :

  1. import java.util.*;
  2.  
  3. public class ArrayListSubList {
  4.     public static void main(String[] args) {
  5.     ArrayList<Integer> list = new ArrayList<Integer>();
  6.       list.add(14);
  7.       list.add(7);
  8.       list.add(21);
  9.       list.add(28);
  10. list.add(35);
  11. list.add(42);    
  12. System.out.println("Original ArrayList : "+list);
  13.      List<Integer> subList = list.subList(1, 3);
  14.      System.out.println("SubList from ArrayList: "+subList);
  15.     }
  16. }
import java.util.*;

public class ArrayListSubList {
	public static void main(String[] args) {
	ArrayList<Integer> list = new ArrayList<Integer>();
      list.add(14);
      list.add(7);
      list.add(21);
      list.add(28);
list.add(35);
list.add(42);	 
System.out.println("Original ArrayList : "+list);
     List<Integer> subList = list.subList(1, 3);
     System.out.println("SubList from ArrayList: "+subList);
	}
}
Note :
The subList method throws IndexOutOfBoundsException – If the specified indexes are out of the range of ArrayList (fromIndex < 0 or toIndex > size). IllegalArgumentException – If the starting index is greater than the end index (fromIndex > toIndex)

.

This is useful if we want to get sublist from the mainlist within some range indexes.

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on