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 first and last elements from Java LinkedList
The first and last elements of a Linked List can be obtained using the methods java.util.LinkedList.getFirst() and java.util.LinkedList.getLast() respectively. Neither of these methods require any parameters.
A program that demonstrates this is given as follows
Example
import java.util.LinkedList;
public class Demo {
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.add("John");
l.add("Sara");
l.add("Susan");
l.add("Betty");
l.add("Nathan");
System.out.println("The first element of the Linked List is : " + l.getFirst());
System.out.println("The last element of the Linked List is : " + l.getLast());
}
}
The output of the above program is as follows
The first element of the Linked List is : John The last element of the Linked List is : Nathan
Now let us understand the above program.
The LinkedList l is created. Then LinkedList.getFirst() and LinkedList.getLast() are used to get the first and last elements of the linked list respectively. A code snippet which demonstrates this is as follows
LinkedList l = new LinkedList();
l.add("John");
l.add("Sara");
l.add("Susan");
l.add("Betty");
l.add("Nathan");
System.out.println("The first element of the Linked List is : " + l.getFirst());
System.out.println("The last element of the Linked List is : " + l.getLast());Advertisements