Enter your E-mail Address below for Free E-mail Alerts right Into your Inbox: -

Wednesday

How to get sublist from an ArrayList in Java

How to get sublist from an ArrayList in Java


We already studied about ArrayList in Java. Now we can see how to sublist an ArrayList. the scenario occurs when a ArrayList contains data that is to be displayed into two areas.
For this we use subList(arg1,arg2);
Example:
/** * author: JOBBERINDIA
 */
package com.jobberindia;
import java.util.*;
/**
 * @author user
 *
 */
public class HelloWorld {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
        List<String> list = new ArrayList<String>();
     
        list.add("Hello");
        list.add("World");
        list.add("Hello1");
        list.add("World2");
        list.add("Hello3");
        list.add("World4");
     
        System.out.println("Data stored in mainlist "+list);
System.out.println("Size of list before removing "+list.size());
ArrayList<String> subList = new ArrayList<String>(list.subList(1, 2));
System.out.println("Data stored in sublist "+subList);
System.out.println("Size of list before removing "+subList.size());
}
}


OutPut:
Data stored in mainlist [Hello, World, Hello1, World2, Hello3, World4]Size of list before removing 6Data stored in sublist [World]
Size of list before removing 1
Possible Errors are IndexOutOfBoundException and IllegalArgumentException.

No comments:

Post a Comment