
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Sublist from LinkedList in Java
The subList of a LinkedList can be obtained using the java.util.LinkedList.subList(). This method takes two parameters i.e. the start index for the sub-list(inclusive) and the end index for the sub-list(exclusive) from the required LinkedList. If the start index and the end index are the same, then an empty sub-list is returned.
A program that demonstrates this is given as follows −
Example
import java.util.LinkedList; import java.util.List; public class Demo { public static void main(String[] args) { LinkedList<String> l = new LinkedList<String>(); l.add("John"); l.add("Sara"); l.add("Susan"); l.add("Betty"); l.add("Nathan"); System.out.println("The LinkedList is: " + l); List subl = l.subList(1, 3); System.out.println("The SubList is: " + subl); } }
Output
The LinkedList is: [John, Sara, Susan, Betty, Nathan] The SubList is: [Sara, Susan]
Now let us understand the above program.
The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows −
LinkedList<String> l = new LinkedList<String>(); l.add("John"); l.add("Sara"); l.add("Susan"); l.add("Betty"); l.add("Nathan"); System.out.println("The LinkedList is: " + l);
The LinkedList.subList() method is used to create a sub-list which contains the elements from index 1(inclusive) to 3(exclusive) of the LinkedList. Then the sub-list elements are displayed. A code snippet which demonstrates this is as follows −
List subl = l.subList(1, 3); System.out.println("The SubList is: " + subl);