- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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);
- Related Articles
- Get first and last elements from Java LinkedList
- How to get sublist of List in Java?
- Implement a stack from a LinkedList in Java
- How to get Sublist of an ArrayList using Java?
- LinkedList in Java
- How to create a Queue from LinkedList in Java?
- Retrieve the last element from a LinkedList in Java
- Remove a specific element from a LinkedList in Java
- How to remove a SubList from an ArrayList in Java?
- Java Program to Remove elements from the LinkedList
- Java Program to Access elements from a LinkedList
- Clear LinkedList in Java
- Remove a range of elements from a LinkedList in Java
- Delete first and last element from a LinkedList in Java
- Create an object array from elements of LinkedList in Java
