![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to Access elements from a LinkedList
In this article, we will understand how to access elements from a linked-list. The java.util.LinkedList class operations perform we can expect for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.
Below is a demonstration of the same −
Suppose our input is −
Input list: [Python, Java, Scala, Java, JavaScript]
The desired output would be −
The element at index 3 is: Java
Algorithm
Step 1 - START Step 2 - Declare a linked list namely input_list. Step 3 - Define the values. Step 4 - Using the built-in function get(), we can access any specific element of the linked list by passing the index value to the function. Step 5 - Display the result Step 6 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
import java.util.LinkedList; public class Demo { public static void main(String[] args) { LinkedList<String> input_list = new LinkedList<>(); input_list.add("Python"); input_list.add("Java"); input_list.add("Scala"); input_list.add("Java"); input_list.add("JavaScript"); System.out.println("The list is defined as: " + input_list); String result_string = input_list.get(3); System.out.print("The element at index 3 is: " + result_string); } }
Output
The list is defined as: [Python, Java, Scala, Java, JavaScript] The element at index 3 is: Java
Example 2
Here, we encapsulate the operations into functions exhibiting object oriented programming.
import java.util.LinkedList; public class Demo { static void get_element(LinkedList<String> input_list, int index){ String result_string = input_list.get(index); System.out.print("The element at index 3 is: " + result_string); } public static void main(String[] args) { LinkedList<String> input_list = new LinkedList<>(); input_list.add("Python"); input_list.add("Java"); input_list.add("Scala"); input_list.add("Java"); input_list.add("JavaScript"); System.out.println("The list is defined as: " + input_list); int index = 3; get_element(input_list, index); } }
Output
The list is defined as: [Python, Java, Scala, Java, JavaScript] The element at index 3 is: Java
Advertisements