This example show how to Get SubList from LinkedList in Java . This example also show us how Obtain sub List from LinkedList using LinkedList subList() method example.
Get SubList from LinkedList Java example
We can get sub list from LinkedList using LinkedList subList() method . LinkedList subList() method returns a view of the portion of this list between the given fromIndex, inclusive, and toIndex, exclusive
Syntax :
public List<E> subList(int fromIndex, int toIndex) {
}
Parameters- subList() method takes following parameters.
fromIndex low endpoint (inclusive) of the subList
toIndex high endpoint (exclusive) of the subList
Returns values- a view of the specified range within this list
Exception- It throws the following exception.
IndexOutOfBoundsException – if an endpoint index value is out of range (fromIndex < 0 || toIndex > size)
IllegalArgumentException – if the endpoint indices are out of order (fromIndex > toIndex)
Let’s see LinkedList subList() method Example in java.
import java.util.LinkedList;
import java.util.List;
public class GetSubList {
public static void main(String[] args) {
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("Mumbai");
linkedList.add("Delhi");
linkedList.add("Noida");
linkedList.add("Gao");
linkedList.add("Patna");
//print linkedlist
System.out.println("Before Remove Element Linklist is = "+linkedList);
/*
* Returns a view of the portion of this list between the
specified fromIndex, inclusive, and toIndex, exclusive.
*/
List<String> list = linkedList.subList(2, 4);
System.out.println("Sublist is ="+list);
}
}
Output:
Before Remove Element Linklist is = [Mumbai, Delhi, Noida, Gao, Patna]
Sublist is =[Noida, Gao]
We have learned how to Obtain sub List from LinkedList. you can see more LinkedList in Java Examples