Write a Java Program to Access elements from a LinkedList.

Java Program to Access elements from a LinkedList.

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Access elements from a LinkedList.
Java Program to Access elements from a LinkedList.

Write a Java Program to Access elements from a LinkedList.

PROGRAM: Java Program to Access elements from a LinkedList.

/*Java Program to Access elements from a LinkedList.*/

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);
}
}

2: Using iterator() method

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(“, “);
}
}
}

3: Using listIterator() method

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(“, “);
}
}
}


		

Leave a Reply

Your email address will not be published. Required fields are marked *