×

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

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

Heart Pattern in Java

Heart Pattern is yet another intricate pattern program, however, due to its complexity, interviewers hardly ever inquire about it. Method for Printing the Heart Number Pattern Put the value of the total row...

2 minutes read.

Sleeping Barber Problem in Java

The barbershop in this issue has one barber, one barber chair, and N chairs for customers in the waiting area. We may demonstrate the issue by keeping with the original...

6 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

Java RMI

What is RMI in Java? A framework for developing distributed Java applications is provided by the RMI (Remote Method Invocation) API. An object can call methods on an object running in...

4 minutes read.

Read JSON file in Java

 To know about reading a JSON file in Java first we must know about the JSON file. JSON: JSON is “JavaScript Object Notation”. The JSON is the simple format for storing and...

3 minutes read.

Empty Statement in Java

The three sorts of statements in Java are control, expression, and declaration statements. Additionally, another statement is referred to as an empty statement. In this section, we will discuss about...

4 minutes read.

How to Convert int to long in Java

How to Convert int to long in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Why to use Enum in Java?

In this article, you will be acknowledged about the Enum in java, its uses and mainly its purpose. Enum has various functionalities. Each of them will be discussed. Enum In a computer...

3 minutes read.

Java Math max() Method

The max() method of Math class returns the greater of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double max(double a, double b)public...

2 minutes read.

How to compare characters in Java

In this tutorial, we will learn about how to compare characters in Java. To compare characters in Java, we will learn about what is a character in Java Char The character is...

4 minutes read.

Java InetAddress class

InetAddress class The InetAddress class refers to the IP address, both IPv4 and IPv6.An instance of an InetAddress consists of an IP address and possibly its corresponding hostname. It provides a method to get the...

9 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.

Transaction Management in java

Definition: A database application is an application that is running against a relational database and executes one or more transactions. A transaction is an executing program that contains some database operations,...

4 minutes read.

Java Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between...

4 minutes read.

Java String endsWith() method

Checks whether this String ends with the specified suffix or not. Syntax public boolean endsWith(String Suffix) Parameter Suffix : It takes suffix as a parameter  i.e. Sequence of characters Returns It returns true when the current...

1 minute read.

Java Boolean Keyword

Boolean keyword In java programming language we basically have two types of primitive data types, Boolean and Numeric (integer and floating-point data types). In this article we are going to learn...

4 minutes read.

Fibonacci Series Program in Java

Fibonacci Series Program in Java using Recursion Fibonacci series is a series whose every term is comprised of adding its previous two terms, barring the first two terms 0 and 1....

3 minutes read.

How to take Array Input in Java

In this tutorial, we will learn about how to take array input in Java. So, before taking inputs let us know what an array is first. Array: An array is a collection...

10 minutes read.

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

5 minutes read.