×

Java LinkedList

LinkedList Java

The Java LinkedList is used to store the elements by using a doubly linked list. It contains the duplicate items, also maintains the order of the insertion, the class is not synchronized in the linked list, and there is no need for shifting in the linked list, so manipulation is faster. It is used as the list, stack, and queue. In the linked list, doubly linked list means we can insert or delete from both sides of the list. It is the collection of nodes and every node consist of three parts.
  1. One part of the data.
  2. The second part to reference the next node.
  3. And third part to reference the previous node.

Declaration of Linked List

The declaration of the linked list is the same as the array list declaration. We can use a generic collection to declare the linked list.
LinkedList<String> li=new LinkedList<String> ();
li- it holds the reference of objects.

The constructor of Linked List

There are two types of Constructor in the linked list:
  1. LinkedList (): This is used to make an empty linked list.
  2. LinkedList (Collection c): This is used to create an ordered list and contains all elements of specified collections.

Methods of Linked List

  1. addFirst (Element e): This method is used to insert the element in the starting of the list.
  2. addLast (Element e): This method is used to insert the element in the last of the list.
  3. addAll (Collection c): It is used to insert all elements at the end of the list.
  4. addAll (int index, Collection c): It is used to insert all elements from the specific index in the list.
  5. add (Element e): It is used to insert the element from the end of the list.
  6. add (Int index, element e): This method is used to insert the element from the specific position in the list.
  7. clone (): This method is used to return the same copy of the list.
  8. remove (): This method is used to remove the first element of the list.
  9. remove (int index): It is used to eliminate the element at a specific position from the list.
  10. remove (object o): It is used to delete the specific element from the list, and it only eliminates the first occurrence of the element.
  11. removeFirst (): This method is used to remove and give back the first element of the list.
  12. removeFirstOccurrence (object o): It is used to eliminate the first occurrence of an element from the list.
  13. removeLast (): This method is used to remove and give back the last element of the list.
  14. removeLastOccurrence (): This method is used to remove the last occurrence of an element from the list.
  15. set (int index, element e): This method is used to set the element at the specific position and replaced that element.
  16. get (int index): This method is used to give back the element at the specific index.
  17. getFirst (): This method is used to give back the first element of the list.
  18. getLast (): This method is used to give back the last element of the list.
  19. clear (): This method is used to remove the elements from the list.
  20. contains (): It is used to check the element is in the list or not. It returns true or false.
  21. IndexOf (object o): It is used to give back the index of the element.
  22. lastIndexOf (object o): It is used to give back the last index of the element.
  23. Size (): This method is used to give the size of the list.

Example of linked list using iterator:

import java.util.*; 
public class LinkedList1 { 
 public static void main (String args []) { 
  LinkedList<String> al=new LinkedList<String> (); 
  al.add ("java"); 
  al.add ("python"); 
  al.add ("angular"); 
  al.add ("mongo db"); 
  al.addFirst ("R");
  Iterator<String> itr=ar.iterator (); 
  while (itr.hasNext ()){ 
   System.out.println (itr.next ()); 
  }   }  }
Output
R
java
python
angular
mongo db

Reverse a list of elements

import java.util.*; 
public class ReverseExample { 
 public static void main (String args []) { 
   LinkedList<String> al=new LinkedList<String> (); 
           al.add ("Mongodb"); 
           al.add ("Nodejs"); 
           al.add ("React"); 
           Iterator i=ll.descendingIterator (); 
           while (i.hasNext ()) { 
          System.out.println (i.next ()); 
        } } }
Output
React
Nodejs
Mongodb

ListIterator Example

import java.util.LinkedList;
import java.util.ListIterator;
public class ListIteratorExample {
public static void main (String[] args) {
    LinkedList<String> al = new LinkedList<String> ();
    al.add ("My");
    al.add ("Name");
    al.add ("is ");
    al.add ("Khan");
    ListIterator listIt =al.listIterator ();
    System.out.println ("Forward iteration :");
    while (listIt.hasNext ()) {
       System.out.println (listIt.next ());
    }
    System.out.println ("\nBackward iteration :");
    while (listIt.hasPrevious ()){
       System.out.println (listIt.previous ());
    }  } }
Output Forward iteration:
My
Name
is
Khan
Backward iteration:
Khan
is
Name
My

Example of using different adds methods in Linked List:

import java.util.*; 
public class AddMethod { 
 public static void main (String args []) { 
 LinkedList<String> al=new LinkedList<String> (); 
           System.out.println ("Initial list of elements: "+al); 
           al.add ("Noida"); 
           al.add ("Aligarh"); 
           al.add ("Mathura"); 
           System.out.println ("After Step1: "+al); 
           al.add (1, "Gujarat"); 
           System.out.println ("After Step2: "+al); 
           LinkedList<String> al2=new LinkedList<String> (); 
           al2.add ("Sonipat"); 
           al2.add ("Ajmer"); 
           al.addAll (al2); 
           System.out.println ("After Step3: "+al); 
            LinkedList<String> al3=new LinkedList<String> ();
           al3.add ("Agra"); 
           al3.add ("Delhi");
           al.addAll (1, al3); 
           System.out.println ("After Step4: "+al);
           al.addFirst ("Gurgaon"); 
           System.out.println ("After Step5: "+al);
           al.addLast ("Himachal Pradesh"); 
           System.out.println ("After Step6: "+al); 
   }  }
Output Initial list of elements: []
After Step1: [Noida, Aligarh, Mathura]
After Step2: [Noida, Gujarat, Aligarh, Mathura]
After Step3: [Noida, Gujarat, Aligarh, Mathura, Sonipat, Ajmer]
After Step4: [Noida, Agra, Delhi, Gujarat, Aligarh, Mathura, Sonipat, Ajmer]
After Step5: [Gurgaon, Noida, Agra, Delhi, Gujarat, Aligarh, Mathura, Sonipat, Ajmer]
After Step6: [Gurgaon, Noida, Agra, Delhi, Gujarat, Aligarh, Mathura, Sonipat, Ajmer, Himachal Pradesh]
Examples of using set and get methods in the Linked List:
import java.util.LinkedList;
public class GetandSet {
public static void main (String [] args) {
LinkedList<String> gs = new LinkedList<String> ();
gs.add ("Item1");
gs.add ("Item2");
gs.add ("Item3");
gs.add ("Item4");
gs.add ("Item5");
gs.add ("Item6");
Object setelement = gs.set (1,"test");
System.out.println (gs);
Object firstElement = gs.getFirst ();
System.out.println ("First Element is: "+firstElement);
Object lastElement =gs.getLast ();
System.out.println ("Last Element is: "+lastElement);
 } }
And Output is:
[Item1, test, Item3, Item4, Item5, Item6]
First Element is: Item1
Last Element is: Item6

Related Topics

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

Java Polymorphism

The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means...

5 minutes read.

Armstrong Number Program in Java

Armstrong Number Program in Java: A positive number is called an Armstrong number if the sum of the cube of each digit is equal to the number itself. There are...

6 minutes read.

Java String format() method

format() method returns a formatted String based on the given locale,specified format and arguments. Syntax: public static String format(String format , Object… args) Parameter: locale : It specifies locale value to be applied on...

2 minutes read.

Java SE vs EE

Java : Java is an independent platform. It works on any kind of operating system. We use java to develop and to focus on large or major projects. The goal of...

3 minutes read.

Callable Statement in Java

The Callable statement in Java is used to call the functions and Stored procedures. Example: If we want to know about the age of a person based on their date of birth,...

3 minutes read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

Addition Program in Java

Addition Program in Java We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand...

3 minutes read.

Java Single Linkedlist

Like arrays, linked lists are a type of linear data structure. Unlike arrays, which store each element in the same location, linked lists employ pointers to connect the elements together. In...

25 minutes read.

Bottom view of a binary tree in Java

The lowest nodes in their horizontal distance are present and referred to as the bottom view of a binary tree. The horizontal distance between the nodes of a binary tree...

4 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

Java Program to print even and odd numbers using 2 threads

Using two threads in a single thread is even odd printing in Java programming with multiple threads. To create code that prints even and odd using two threads, we must...

2 minutes read.

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search...

3 minutes read.

Catalan number in Java

In general mathematics, Catalan numbers can be defined as the sequence of natural numbers that frequently occur in counting problems often encountered in recursively defined objects. Mathematical formula of Catalan number Coming...

3 minutes read.

Java Write File

In this post, we'll examine various Java programming methods for writing into files. Since this class is character-oriented due to how it is used in file handling in Java, it...

4 minutes read.

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

Sphenic Number in Java

In this section, we will learn what is a sphenic number is and show you how to write Java programmes to determine if a specific number are sphenic or not....

3 minutes read.

How to run Java Program?

How to run Java Program In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad. In order to run a Java program, we...

2 minutes read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

Tetranacci Number in Java

This article mainly describes tetranacci number identification and the Java Program for Tetranacci numbers. Tetranacci number Tetranacci numbers and Fibonacci numbers are related. The key contrast is that a Tetranacci number depends...

3 minutes read.