×

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

Polygonal Number in Java

What does a Java Polygonal Number Mean? In mathematics, a polygonal number refers to a number that is expressed through dots or pebbles arranged in a regular polygonal pattern. Alphas are...

4 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

Java Math floorMod() Method

The floorMod() method of Math class returns the floor modulus of the specified arguments. It firstly divides the dividend and divisor and then returns an integer that is equal to...

1 minute read.

JDBC Program in Java

JDBC Program in Java JDBC is an API that defines how a client may access a database. It is a part of Java Standard Edition (Java SE). JDBC stands for Java...

4 minutes read.

RMI program in Java

Remote Method Invocation is what it stands for. An object can call the method of another object in a different space address using the RMI API, which may be on the...

3 minutes read.

Program to Find the Common Elements between two Arrays in Java

In this article, we are going to learn how to find the common elements between two arrays using Java. Here, we use different approaches in Java to find the common...

3 minutes read.

Java AWT

Java AWT Java programming is used to develop different types of applications like window-based applications, web applications, Enterprise applications, or mobile applications. For creating standalone applications, Java AWT API is used....

11 minutes read.

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it. Transient variable By introducing the transitory keyword, we...

3 minutes read.

Least Operator to Express Number in Java

In this article, we will learn about how to obtain a target number using a single number or a single integer by leveraging least operators in Java. There can be...

3 minutes read.

Pancake Sorting in Java

In the pancake sorting method, the array must be sorted using just one operation, which is: Flip the arrays arr at index 0 to index j by using flipArr(arr, h). Other sorting...

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

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

How to Send SMS in Java with Example

Sending SMS messages in Java is a fairly common task, and there are a number of libraries and APIs available to help you do it. One popular option is to...

2 minutes read.

Character Array in Java

A character array is an array which holds values of character data types. It is different from a string array. The character array, string, and StringBuffer classes in the Java...

4 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

New Features of Java 14

 Features like Switch expressions and text blocks which are previewed in Java 13 version are standardized in Java 14. Features in Java 14 Switch ExpressionText BlocksRecordsNull Pointer ExceptionsInstance ofPackaging ToolGarbage collectors 1.Switch Expressions Switch...

3 minutes read.

Relatively Prime in Java

In this article, you will be very well equipped with a knowledge of a relatively prime number and also Java programs to determine whether a given integer is a relatively...

4 minutes read.

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection...

5 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.