How to Get Sublist of ArrayList in Java


The example aims to show how to get sublist of ArrayList with subList method in Java.

Source Code

package com.beginner.examples;

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

public class SubListOfArrayListExample {

	
	public static void main(String[] args) {
		
		ArrayList al = new ArrayList();
		
		al.add("A");
		al.add("B");
		al.add("C");
		al.add("D");
		al.add("E");
		al.add("F");
		
		/*
		 * This method intercepts all elements of 2-4,
		 *  but does not include index 4
		 */
		List subAl= al.subList(2, 4);
		
		System.out.println("al:"+al);
		System.out.println("subAl:"+subAl);

	}

}

Output:

al:[A, B, C, D, E, F]
subAl:[C, D]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments