Thursday, April 26, 2012

Get Sub List of Java ArrayList Example

package com.subList.demo;

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

/**
 * This Java Example shows how to get sub list of java ArrayList using subList method.
 *
 * @author abdul
 */
public class SubListDemo {

    public static void main(String args[]) {

        //create an ArrayList object
        List<String> list = new ArrayList<String>();
        int range = 4;

        //Add elements to Arraylist
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        list.add("E");
        list.add("F");
        list.add("G");
        list.add("H");
        list.add("I");
        list.add("J");
        list.add("K");
        list.add("L");
        list.add("M");
        list.add("N");
        list.add("O");
        display("Displaying all elements of the list : ", list);

        if(list.size() > range) {
            int from = 0;
            int to = range;
            List<String> lt = null;
            do {
                //Check whether "to" value never exceeds from the list size
                //otherwise it would throw error while fetching subList
                if(list.size() - from > range ) {

                    // 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
                    lt = list.subList(from, to);

                    display("SubList from " + from + " to " + to, lt);
                } else {
                    lt = list.subList(from, list.size());
                    display("SubList from " + from + " to " + list.size(),lt);
                }
                from += range;
                to += range;
            }while(from < list.size());
        } else {
            display("Displaying all elements of the list : " , list);
        }
    }

    /**
     * Display elements of sub list.
     * @param message
     * @param list sublist of the list to print
     */
    private static void display(String message,List<String> list) {
        System.out.println(message + "\nList: " + list);
    }
}

Output:
Displaying all elements of the list :
List: [A, B, C, D, E, F, G, H, I, J, K, L, M, N, O]
SubList from 0 to 4
List: [A, B, C, D]
SubList from 4 to 8
List: [E, F, G, H]
SubList from 8 to 12
List: [I, J, K, L]
SubList from 12 to 15
List: [M, N, O]


Related link:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/List.html

No comments:

Post a Comment

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...