How to Get Sublist of LinkedList in Java?
Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part.
Given a list of elements present in a LinkedList, we need to find the elements of a sublist of the given range.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
The elements of the LinkedList are: [3, 5, 2, 1, 7, 8] Enter the start and end of the required sublist: start position -> 1 end position -> 4 The required SubList is: [5, 2, 1] where start position is inclusive and the end position is exclusive
Approach: Using default subList() method present in LinkedList class of util package.
This one is quite simple and pretty straightforward. We basically use java.util.LinkedList.subList() .
public List subList(int fromIndex, int toIndex)
Parameters: This method takes the following argument as a parameter.
- fromIndex – low endpoint (inclusive) of the subList
- toIndex – high endpoint (exclusive) of the subList
Returns Value: This method returns a view of the specified range within this list.
- Enter the elements in the LinkedList or procure the LinkedList.
- Enter the starting of the range(inclusive, 0 based) of the subList that you want to find.
- Enter the ending of the range(exclusive, 0 based).
- Use the start and end as parameters of the subList() method and assign it to a new list to store this sublist.
The elements of the LinkedList are: [apple, mango, peach, guava, banana, lichi] Enter the start and end of the required sublist: The required SubList is: [peach, guava, banana]
Example 2: To get the sublist from the Linked List of LinkedLists.
The elements of the LinkedList are: [[8, 0], [10, 4, 3, 5], [1, 2, 9]] Enter the start and end of the required sublists: The required SubList is: [[10, 4, 3, 5], [1, 2, 9]]