Sometimes we need subList from ArrayList in Java. For example, we have an ArrayList of 10 objects and we only need 5 objects or we need an object from index 2 to 6, these are called subList in Java. Java collection API provides a method to get SubList from ArrayList. In this Java tutorial, we will see an example of getting SubList from ArrayList in Java. In this program, we have an ArrayList which contains 4 String objects. Later we call ArrayList.subList() method to get part of that List.
SubList Example Java
Here is complete code example of getting SubList in JavaJava Program to get the part of a List
import java.util.ArrayList;
import java.util.List;
/**
* Java program to get SubList or a range of list from Array List in Java
*
*/
public class GetSubListExample {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
//Add elements to Arraylist
arrayList.add("Java");
arrayList.add("C++");
arrayList.add("PHP");
arrayList.add("Scala");
/*
subList Method returns sublist from list with starting index to end index-1
*/
List<String> lst = arrayList.subList(1,3);
//display elements of sub list.
System.out.println("Sub list contains : ");
for(int i=0; i< lst.size() ; i++)
System.out.println(lst.get(i));
//remove one element from sub list
Object obj = lst.remove(0);
System.out.println(obj + " is removed from sub list");
//print original ArrayList
System.out.println("After removing " + obj + " from sub list, original ArrayList contains : ");
for(int i=0; i< arrayList.size() ; i++)
System.out.println(arrayList.get(i));
}
}
import java.util.List;
/**
* Java program to get SubList or a range of list from Array List in Java
*
*/
public class GetSubListExample {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
//Add elements to Arraylist
arrayList.add("Java");
arrayList.add("C++");
arrayList.add("PHP");
arrayList.add("Scala");
/*
subList Method returns sublist from list with starting index to end index-1
*/
List<String> lst = arrayList.subList(1,3);
//display elements of sub list.
System.out.println("Sub list contains : ");
for(int i=0; i< lst.size() ; i++)
System.out.println(lst.get(i));
//remove one element from sub list
Object obj = lst.remove(0);
System.out.println(obj + " is removed from sub list");
//print original ArrayList
System.out.println("After removing " + obj + " from sub list, original ArrayList contains : ");
for(int i=0; i< arrayList.size() ; i++)
System.out.println(arrayList.get(i));
}
}
Output:
Sub list contains :
C++
PHP
C++ is removed from sub list
After removing C++ from sub list, original ArrayList contains :
Java
PHP
Scala
List of Java homework exercise program from java67 blog
No comments:
Post a Comment
Feel free to comment, ask questions if you have any doubt.