LinkedList poll method examples
LinkedList provides 3 methods to get elements and remove them from the list.
1 2 3 | E poll() E pollFirst() E pollLast() |
You can get the java doc for this methods Here
lets see the LinkedList poll method examples
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | package com.kscodes.collections.linkedList; import java.util.LinkedList; public class LinkedListPollMethods { public static void main(String[] args) { LinkedList<String> linkedList = new LinkedList<>(); // Use add(E e) to add elements linkedList.add("Java"); linkedList.add("JSP"); linkedList.add("Spring MVC"); linkedList.add("Hibernate"); // Iterate LinkedList using For Loop System.out.println("****Iterating LinkedList ::"); for (String element : linkedList) { System.out.println(element); } // Use poll() to get the head of list and then remove It. // Here we will get "Java" String poll = linkedList.poll(); System.out.println("**Using poll() - " + poll); // Use pollFirst() to get the First element of list // Since we removed "Java", now we will get "JSP" as the first element String pollFirst = linkedList.pollFirst(); System.out.println("**Using pollFirst() - " + pollFirst); // Use pollLast() to get the Last element of list // here we will get "Hibernate" String pollLast = linkedList.pollLast(); System.out.println("**Using pollLast() - " + pollLast); // Lets re print the list again see that some elements were removed // We have removed "Java", "JSP" and "Hibernate" System.out.println("****After using poll methods - Iterating LinkedList ::"); for (String element : linkedList) { System.out.println(element); } } } |
Output
1 2 3 4 5 6 7 8 9 10 | ****Iterating LinkedList :: Java JSP Spring MVC Hibernate **Using poll() - Java **Using pollFirst() - JSP **Using pollLast() - Hibernate ****After using poll methods - Iterating LinkedList :: Spring MVC |