×

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

Java Thread class

Thread class The thread represents a part of the process. Every process can have multiple associated threads in which every thread may execute the same or different job. By default, each thread assigns...

16 minutes read.

How to Set Java_home in Linux

To set the Java_home in Linux, we must follow several steps to make us understand it easily.  Java follows the principle called WORA (write once run anywhere). We know that java...

3 minutes read.

Java String replaceAll() method

Java String replaceAll() method returns a String replacing all the sequence of characters matching regular expression i.e regex and replacement string. Syntax: public String replaceAll(String regex, String replacement) Parameters: regex : regular expression replacement :...

1 minute read.

Add numbers represented by Linked Lists in Java

For calculating the sum of the two numbers that are represented by a linked list, and then store the result in a new linked list. A linked list's head node...

7 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

Hollow Diamond Pattern in Java

Why are patterns important? Programmers frequently create Java pattern programs to practice coding and ace interviews. Interviewers frequently test candidates' logical reasoning and implementation by asking about pattern programs. Hollow Diamond Pattern The...

7 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

Get year from date in Java

The getYear() method of the Java date class returns a number calculated by deducting 1900 from the year that contains or starts with the instant in time represented by this...

4 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.

Java String Concatenation

Java String Concatenation Java programming provide a way to combine multiple strings into a single string. It is called as String Concatenation. There are different ways to concatenate two or more...

4 minutes read.

Java Import Keyword

Java's import keyword used in the code that follows the import statement, a Java class is declared. Once a Java class is declared, it is possible to use the class...

6 minutes read.

Undo and Redo Operations in Java

Undo and redo operation are the most widely used operation while dealing with file. In this section, we will discuss how to implement undo and redo operation in Java. Undo Redo...

2 minutes read.

Java Developer

Who is a Java Developer? A Java developer is a skilled programmer who works on commercial applications, software, and webpages.  Java developers can work in two different areas: Operating system development:...

3 minutes read.

3N+1 problem program in Java

The 3N+1 problem is a hypothesis in the field of abstract mathematics (not yet proven). Collectively known as the Collatz problem. This tutorial will describe about the 3N+1 problem and...

3 minutes read.

Java Math abs() Method

The abs() method of Math class returns the absolute value of the argument where the argument can be int, double, float, long. Syntax public static int abs(int a) public static float abs(float a) public...

2 minutes read.

Java Primitive Data Types

Primitive data types are the simplest data types in a programming language. They’re predefined in the language. The names of the primitive types are quite descriptive of the values that...

2 minutes read.

Java Thread Dump Analyzer

Thread: A thread is a PC program that is stacked into the PC's memory and is under execution. It tends to be executed by a processor or a bunch of processors....

15 minutes read.

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

Java Math signum() Method

The signum() method of Java Math class returns the signum function of the value. Syntax: public static double signum(double d)public static float signum (float d) Parameters: The parameter ‘d’ represents the floating-point value whose...

2 minutes read.

Difference between Aggregation and Composition in Java

What is Aggregation? Before we start discussing Aggregation, we have to know some general information about our classes in java. Generally we have two members in our classes , the first...

8 minutes read.