In this tutorial we will see an example on how to get first and last element from LinkedList.
Example
Here we have a LinkedList of String type and we are getting first and last element from it using getFirst() and getLast() methods of LinkedList class. Method definition and description are as follows:
1) public E getFirst(): Returns the first element in this list.
2) public E getLast(): Returns the last element in this list.
import java.util.LinkedList;
public class GetFirstAndLast {
public static void main(String[] args) {
// Create a LinkedList
LinkedList<String> linkedlist = new LinkedList<String>();
// Add elements to LinkedList
linkedlist.add("Item1");
linkedlist.add("Item2");
linkedlist.add("Item3");
linkedlist.add("Item4");
linkedlist.add("Item5");
linkedlist.add("Item6");
// Getting First element of the List
Object firstElement = linkedlist.getFirst();
System.out.println("First Element is: "+firstElement);
// Getting Last element of the List
Object lastElement = linkedlist.getLast();
System.out.println("Last Element is: "+lastElement);
}
}
Output:
First Element is: Item1 Last Element is: Item6
Leave a Reply