

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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());
- Related Questions & Answers
- 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
- Get first and last elements of a list in Python
- Get SubList from LinkedList in Java
- Get all rows apart from first and last in MySQL
- Retrieve the last element from a LinkedList in Java
- Java Program to Access elements from a LinkedList
- Java Program to Remove elements from the LinkedList
- Get the last node of the LinkedList in C#
- Get last N elements from given list in Python
- Remove a range of elements from a LinkedList in Java
- Create an object array from elements of LinkedList in Java
- Get last key from NavigableMap in Java
Advertisements