- 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 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());
- Related Articles
- Get first and last elements from Vector in Java
- Delete first and last element from a LinkedList in Java
- How to get first and last elements from ArrayList in Java?
- Java Program to Get First and Last Elements from an Array List
- Python program to get first and last elements from a tuple
- Get SubList from LinkedList in Java
- Retrieve the last element from a LinkedList in Java
- Get first and last elements of a list in Python
- Java Program to Remove elements from the LinkedList
- Java Program to Access elements from a LinkedList
- Get all rows apart from first and last in MySQL
- Python Program to get first and last element from a Dictionary
- Get the last node of the LinkedList in C#
- Remove a range of elements from a LinkedList in Java
- Create an object array from elements of LinkedList in Java

Advertisements