Example 1: Access elements from a linkedlist
import java.util.LinkedList;
class Main {
public static void main(String[] args) {
LinkedList<String> languages = new LinkedList<>();
// add elements in the LinkedList
languages.add("Python");
languages.add("Java");
languages.add("JavaScript");
System.out.println("LinkedList: " + languages);
// get the element from the LinkedList
String str = languages.get(1);
System.out.print("Element at index 1: " + str);
}
}
Output
LinkedList: [Python, Java, JavaScript] Element at index 1: Java
In the above example, we have used the get()
method with parameter 1. Here, the method returns the element at index 1.
Example 2: Using iterator() method
We can also use the iterator() method to iterate over the elements of a linkedlist. We must import java.util.Iterator
package to use this method. For example,
import java.util.LinkedList;
import java.util.Iterator;
class Main {
public static void main(String[] args) {
LinkedList<String> animals= new LinkedList<>();
// Add elements in LinkedList
animals.add("Dog");
animals.add("Horse");
animals.add("Cat");
// Creating an object of Iterator
Iterator<String> iterate = animals.iterator();
System.out.print("LinkedList: ");
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
}
}
}
Output
LinkedList: Dog, Cat, Horse,
Here,
hasNext()
- returnstrue
if there is a next elementnext()
- returns the next element
To learn more about Iterator
, visit the Java Iterator Interface.
Example 3: Using listIterator() method
We can also use the listIterator()
method to iterate over the elements of a LinkedList. To use this method, we must import java.util.ListIterator
package.
import java.util.LinkedList;
import java.util.ListIterator;
class Main {
public static void main(String[] args) {
LinkedList<String> animals= new LinkedList<>();
// Add elements in LinkedList
animals.add("Dog");
animals.add("Horse");
animals.add("Cat");
// Create an object of ListIterator
ListIterator<String> listIterate = animals.listIterator();
System.out.print("LinkedList: ");
while(listIterate.hasNext()) {
System.out.print(listIterate.next());
System.out.print(", ");
}
// Iterate backward
System.out.print("\nReverse LinkedList: ");
while(listIterate.hasPrevious()) {
System.out.print(listIterate.previous());
System.out.print(", ");
}
}
}
Output
LinkedList: Dog, Horse, Cat, Reverse LinkedList: Cat, Horse, Dog,
Here,
hasNext()
- returnstrue
if there is a next elementnext()
- returns the next elementhasPrevious()
- returnstrue
if there exist previous elementsprevious()
- returns the previous element
To learn more about ListIterator
, visit Java ListIterator Interface.
Note: The listIterator()
method is more preferred than iterator()
. This is because it allows you to iterate backward as well.