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
Retrieve the last element from a LinkedList in Java
The last element of a Linked List can be retrieved using the method java.util.LinkedList.getLast() respectively. This method does not require any parameters and it returns the last element of the LinkedList.
A program that demonstrates this is given as follows −
Example
import java.util.LinkedList;
public class Demo {
public static void main(String[] args) {
LinkedList<String> l = new LinkedList<String>();
l.add("Andy");
l.add("Sara");
l.add("James");
l.add("Betty");
l.add("Bruce");
System.out.println("The last element of the Linked List is : " + l.getLast());
}
}
Output
The last element of the Linked List is : Bruce
Now let us understand the above program.
The LinkedList l is created. LinkedList.add() is used to add the elements to the LinkedList. Then LinkedList.getLast() is used to retrieve the last element of the linked list. A code snippet which demonstrates this is as follows −
LinkedList<String> l = new LinkedList<String>();
l.add("Andy");
l.add("Sara");
l.add("James");
l.add("Betty");
l.add("Bruce");
System.out.println("The last element of the Linked List is : " + l.getLast());Advertisements