Java – How to get sub-list from ArrayList ?

In this article, we will discuss an example on how to get sub list from ArrayList

Sub list is the portion of an ArrayList by specifying range

1. Sub list from ArrayList using subList() method :

Method signature:

List subList(int fromIndex, int toIndex);
  • Returns portion of invoking list between specified fromIndex and toIndex,
  • where fromIndex is inclusive & toIndex is exclusive
  • Note: If fromIndex and toIndex are equal or same, then returned list is empty

GetSubListFromArrayList.java

package in.bench.resources.java.collections;

import java.util.ArrayList;
import java.util.List;

public class GetSubListFromArrayList {

	public static void main(String[] args) {

		// creating ArrayList object of type String
		ArrayList<String> al = new ArrayList<String>();

		// adding elements to ArrayList object
		al.add("Sundar Pichai");
		al.add("Satya Nadella");
		al.add("Shiv Nadar");
		al.add("Shantanu Narayen");
		al.add("Sundar Pichai"); // duplicate object
		al.add("Francisco D’Souza");
		al.add(null); // null is allowed

		System.out.println("Original size of ArrayList is : "
				+ al.size());

		// Iterating using for-loop
		System.out.println("\nIterating ArrayList using for-loop\n");
		for(int index = 0; index < al.size(); index++) {
			System.out.println(al.get(index));
		}

		// getting sub-list
		List<String> subList = al.subList(1, 6);

		System.out.println("\n\n\nSub List size is : "
				+ subList.size());

		// Iterating using enhanced for-loop
		System.out.println("\nIterating Sub List\n");
		for(String str : subList) {
			System.out.println(str);
		}
	}
}

Output:

Original size of ArrayList is : 7

Iterating ArrayList using for-loop

Sundar Pichai
Satya Nadella
Shiv Nadar
Shantanu Narayen
Sundar Pichai
Francisco D’Souza
null

Sub List size is : 5

Iterating Sub List

Satya Nadella
Shiv Nadar
Shantanu Narayen
Sundar Pichai
Francisco D’Souza

From above example, ArrayList

  • allows duplicate elements
  • null object is allowed
  • while iterating insertion-order is maintained

Q) What will subList returns, when both from-index and to-index are same ?

  • Returns an empty list

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - How to check whether particular element is present in an ArrayList ?
Java - How to delete an element and delete all elements of an ArrayList