×

Java LinkedHashSet

LinkedHashSet in Java with Example

Java LinkedHashSet extends HashSet and Implements the Set interface. It doesn’t contain only duplicate values like HashSet. It also permits the null elements. It maintains the order of insertion. It returns the elements in the order in which they are inserted. It also maintains the linked list of the elements in the set. The syntax of the LinkedHashSet is:
LinkedHashSet<String> hs= new LinkedHashSet<String> ();
It also has two factors which affect the performance of LinkedHashSet-> Load Factor and Initial Capacity. Difference between HashSet and LinkedHashSet:

Categories

HashSet

LinkedHashSet

Internal Working Internally uses HashMap for storing objects. Internally uses LinkedHashMap for storing objects.
Order Not maintain the insertion order. Maintain the insertion order.
Complexity The complexity is O(1). The complexity is O(1).
Performance Its performance is better than LinkedHashSet. Its performance is slower than HashSet due to the insertion order.
Compare It uses equals () and hashCode (). It also uses equals () and hashCode () for comparing.
Null Elements It allows only one null element. It allows only one null element.
When to use If you want unique elements but don’t want to maintain the order of insertion. It used when to want to maintain the insertion order of the elements.
Syntax HashSet<String> hs= new HashSet<String> (); LinkedHashSet<String> h= new LinkedHashSet<String> ();
 Similarities between HashSet and LinkedHashSet:
  1. The HashSet and LinkedHashSet implements Set interface. Hence, they are not allowed to keep the duplicate value.
  2. HashSet and LinkedHashSet both are cloneable and Serializable.
  3. You have to make it externally synchronize if you want to use multi-threading environment because both do not thread safe.

Time Complexity of LinkedHashSet

LinkedHashSet uses the HashTable Data Structure. The Complexity of the LinkedHashSet is O(1) time for adding, removing, and retrieving operations.

Constructors of LinkedHashSet

  1. LinkedHashSet (): It is used to create the default HashSet.
  2. LinkedHashSet (Collection c): It is used to initialize with elements of the collection.
  3. LinkedHashSet (int size): It is used to initialize the size of LinkedHashSet.
  4. LinkedHashSet (Int Capacity, float Loadfactor): This is used to initialize both the capacity and load factor.
Methods of LinkedHashSet
  1. add (object o): This method is used to add the elements in HashSet.
Example:
import java.util. LinkedHashSet;
public class AddExample {
public static void main (String args []) {
LinkedHashSet<Integer> lh= new LinkedHashSet<Integer> ();
lh.add (99);
lh.add (7);
lh.add (0);
lh.add (67);
lh.add (66);
System.out.println (lh);
}
}
Output:
[99, 7, 0, 67, 66]
  1. remove (object o): Used to remove the elements from the set.
Example:
import java.util. LinkedHashSet;
public class RemoveExample {
public static void main (String args []) {
LinkedHashSet<Integer> lh= new LinkedHashSet<Integer> ();
lh.add (99);
lh.add (7);
lh.add (0);
lh.add (67);
lh.add (66);
System.out.println (lh);
lh.remove (0);
System.out.println ("After removing: "+ lh);
}
}
Output:
[99, 7, 0, 67, 66]
After removing:
[99, 7, 67, 66]
  1. contains (object o): It returns true if the element found in the set.
Example:
import java.util. LinkedHashSet;
public class ContainExample {
public static void main (String args []) {
LinkedHashSet<Integer> lh= new LinkedHashSet<Integer> ();
lh.add (99);
lh.add (7);
lh.add (0);
lh.add (67);
lh.add (66);
System.out.println (lh);
System.out.println ("Does the set contain 67?"+ lh.contains (67));
System.out.println ("Does the set contain 99?”+ lh.contains (99));
System.out.println ("Does the set contain 88?”+ lh.contains (88));
}
}
Output:
[99, 7, 0, 67, 66]
Does the set contain 67? true Does the set contain 99? true Does the set contain 88? false
  1. isEmpty (): It returns true if the set is empty otherwise false.
Example:
import java.util. LinkedHashSet;
public class EmptyExample {
public static void main (String args []) {
LinkedHashSet<Integer> lh= new LinkedHashSet<Integer> ();
lh.add (99);
lh.add (7);
lh.add (0);
lh.add (67);
lh.add (66);
System.out.println (lh);
System.out.println ("Is the set empty: " + lh.isEmpty ());
lh.clear ();
System.out.println ("Is the set empty: " + lh.isEmpty ());
}
}
Output:
[99, 7, 0, 67, 66]
Is the set empty: false Is the set empty: true
  1. int size (): This method is used to return the number of elements in the set.
Example:
import java.util. LinkedHashSet;
public class SizeExample {
public static void main (String args []) {
LinkedHashSet<Integer> lh= new LinkedHashSet<Integer> ();
lh.add (99);
lh.add (7);
lh.add (0);
lh.add (67);
lh.add (66);
System.out.println (lh);
System.out.println ("The size of the element: "+lh.size ());
lh.clear ();
System.out.println ("Set contain: " + lh.size () +" elements");
}
}
Output:
[99, 7, 0, 67, 66]
The size of the element: 5 Set contain: 0 elements
  1. retainAll (): It is used to retain the entire element from the collection and show only those elements that are same in both Sets.
Example:
import java.util. LinkedHashSet;
public class RetainAllExample {
public static void main (String args []) {
LinkedHashSet<Integer> lh= new LinkedHashSet<Integer> ();
lh.add (99);
lh.add (7);
lh.add (0);
lh.add (67);
lh.add (66);
System.out.println ("The element before retainAll operation: "+ lh);
LinkedHashSet<Integer> lh2= new LinkedHashSet<Integer> ();
lh2.add (100);
lh2.add (78);
lh2.add (67);
lh2.add (17);
lh2.add (66);
System.out.println ("The element for retain: "+lh2);
lh.retainAll (lh2);
System.out.println ("The elements after retainAll operation: "+lh);
}
}
Output: The element before retainAll operation:
[99, 7, 0, 67, 66]
The element for retain:
[100, 78, 67, 17, 66]
The elements after retainAll operation:
[67, 66]
  1. hashCode (): It is used to get the hashcode value of the instance of the LinkedHashSet.
Example:
import java.util. LinkedHashSet;
public class HashCodeExample {
public static void main (String args []) {
LinkedHashSet<Integer> lh= new LinkedHashSet<Integer> ();
lh.add (99);
lh.add (7);
lh.add (0);
lh.add (67);
lh.add (66);
System.out.println ("The element: "+ lh);
System.out.println ("The hashcode value: "+lh.hashCode ());
}
}
Output: The element:
[99, 7, 0, 67, 66]
The hashcode value:
239

Difference between LinkedHashSet and LinkedHashMap:

LinkedHashSet

LinkedHashMap

1. It is used to store the collection of elements. 1. It is used to store the key-value pairs.
2. It implements HashSet. 2. It Implements HashMap.
3. It doesn’t store duplicates values. 3. It stores unique keys but can store duplicate values.
4. The syntax and to add the elements in the Set is: LinkedHashSet<String> lhs= new LinkedHashSet<String> (); lhs.add(“Welcome”); lhs.add(“to”); lhs.add(“TutorialAndExample”); 4.The syntax and the add the elements in the map is: LinkedHashMap<String> lhm= new LinkedHashMap<String> (); lhm.put (“Welcome”,5); lhm.put (“to”,6); lhm.put(“TutorialAndExample”,12);

 Example using iterator() method

import java.util.*;
public class SizeExample {
public static void main (String args []) {
LinkedHashSet<Integer> lh= new LinkedHashSet<Integer> ();
lh.add (99);
lh.add (7);
lh.add (0);
lh.add (67);
lh.add (66);
System.out.println ("The element: "+ lh);
Iterator<Integer> i=lh.iterator (); 
while (i.hasNext ()) 
 { 
 System.out.println (i.next ()); 
 } 
}
}
Output: The element:
[99, 7, 0, 67, 66]
99
7
0
67
66

Related Topics

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

Class vs Object in Java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Java Class Keyword

We know that java is object-oriented programming language which contains the essential key concepts such as classes and objects etc to have clear idea about the object-oriented programming.Java is mainly...

3 minutes read.

Hello Program in Java

Hello Program in Java The Hello program in Java displays the word Hello on the console. It is the basic program in Java. In this section, we will learn different ways...

3 minutes read.

How to Split String by Comma in Java

strsplit() technique permits you to break a string given the explicit Java string delimiter. The Java string split property is frequently a space or a comma(,) that you want to...

7 minutes read.

Constructor Program in Java

Constructor Program in Java In Java, a constructor is a piece of code that is used to create an object. A constructor is called implicitly when an object is created in...

7 minutes read.

Array and String based questions in Java

1. What is an Array in Java? A collection of identical data types is referred to as an array. There can be no separate data kinds. It supports the storage of...

4 minutes read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.

Thread Program in Java

Thread Program in Java Thread program in Java is the continuation of multithreading program in Java. In this topic, we will learn about the usage of threads, race condition in multithreading,...

8 minutes read.

Composition in Java

Composition Java uses the composition method to implement a has-a connection. Composition allows us to reuse code in the same way that Java inheritance does. The "is-a" relationship is implemented using the...

3 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 minutes read.

Java Output Formatting

Sometimes we want a program's output to be displayed in a specific format. The printf () function in the C programming language can be used to achieve this. We will...

4 minutes read.

How to create a mirror image of a 2D array in Java

Problem Statement We have provided a list of m x n. here m indicates rows, and n indicates columns). Printing the fresh matrices should result in a mirror reflection of an...

2 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

Jdoodle Java

Everything is instantaneous and fast-paced in the modern world. Online compilers available via the internet are immensely helpful for programmers seeking to learn a new programming language but lacking the...

4 minutes read.

Java Socket Programming

Java Socket Programming Socket programming is used for the communication between the applications, i.e., client and server running on different JRE may be connection-oriented or connectionless. The client program can be designed using the...

8 minutes read.

JDK | Java Development Kit

Java Development Kit (JDK) The Java Development Kit is a software development environment used to create Java applications. The JDK includes JRE (Java Runtime Environment), an interpreter (java), a compiler (javac),...

3 minutes read.

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.