How to Convert ArrayList to LinkedHashSet in Java?
Last Updated :
20 Sep, 2021
ArrayList is a data structure that overcomes the shortcomings of the common array in Java wherein the size has to be explicitly specified beforehand. The length of the array data structure cannot be modified which is taken care of the ArrayList data structure. This data structure is also known as the dynamic array and can grow or be modified as the need be. It is a class under the Collections framework and can be included in the java program by importing java.util package.
LinkedHashSet is an enhanced version of the traditional HashSet class in Java by providing the added functionality of ordering which was missing in the HashSet. It maintains the order in which the elements were inserted into it, unlike the HashSet where the ordering was unpredictable. It is implemented using a doubly-linked list and can be iterated over using the iterator.
This article deals with the conversion of ArrayList to LinkedHashSet using 4 different approaches which are listed as follows :
- Passing the ArrayList as a parameter during the initialization of the LinkedHashSet constructor.
- Using the addAll() method of the LinkedHashSet class.
- Using the add() method of the LinkedHashSet class while iterating over all the elements of the ArrayList.
- Using stream to first convert the ArrayList to Set which is further converted to LinkedHashSet.
Approach 1
Using this approach we merely, pass the ArrayList as a parameter while initializing the LinkedHashSet class
Syntax
LinkedHashSet(Collection C): Used in initializing the HashSet with the elements of the collection C.
LinkedHashSet<E> hs = new LinkedHashSet<E>(Collection c);
Example
Java
// java program to convert ArrayList
// to LinkedHashSet
// importing the utils package
import java.util.*;
class GFG {
// defining the method
void arrayListToLinkedHashSet()
{
// initializing the ArrayList
ArrayList<String> arrayList = new ArrayList<>();
// adding values in the ArrayList
arrayList.add("Geeks");
arrayList.add("For");
arrayList.add("Geeks");
// printing the list
System.out.println("The array list : " + arrayList);
// initializing the LinkedHashSet class
// passing the ArrayList as parameter
LinkedHashSet<String> linkedHashSet
= new LinkedHashSet<String>(arrayList);
// printing the LinkedHashSet
System.out.println("The converted "
+ "Linked Hash Set : "
+ linkedHashSet);
}
// Driver Code
public static void main(String[] args)
{
// instantiating the class
GFG ob = new GFG();
// calling the method
ob.arrayListToLinkedHashSet();
}
}
OutputThe array list : [Geeks, For, Geeks]
The converted Linked Hash Set : [Geeks, For]
Explanation:
The ArrayList contains three entries which are [Geeks, For, Geeks]. This is converted to an ordered set and only contains two values: Geeks and For. Since Set don't allow multiple similar values.
Approach 2
Using this approach, we use the predefined method addAll() of the LinkedHashSet class after initializing it to populate the LinkedHashSet.
Syntax:
LinkedHashSet.addAll(Collection C)
Parameters: Parameter C is a collection of any type that is to be added to the set.
Return Value: The method returns true if it successfully appends the elements of the collection C to this Set otherwise it returns False.
Example
Java
// java program to convert ArrayList
// to LinkedHashSet
// importing the java.utils package
import java.util.*;
class GFG {
// defining the method
void arrayListToLinkedHashSet()
{
// initializing the ArrayList
ArrayList<String> arrayList = new ArrayList<>();
// filling the ArrayList with values
arrayList.add("Geeks");
arrayList.add("For");
arrayList.add("Geeks");
// printing the list
System.out.println("The Array List : " + arrayList);
// initializing the LinkedHashSet
LinkedHashSet<String> linkedHashSet
= new LinkedHashSet<>();
// using the addAll() to
// fill the HashSet
linkedHashSet.addAll(arrayList);
// printing the LinkedHashSet
System.out.println("The Linked "
+ "Hash Set : " + linkedHashSet);
}
// Driver Code
public static void main(String[] args)
{
// instantiating the class
GFG ob = new GFG();
// calling the method
ob.arrayListToLinkedHashSet();
}
}
OutputThe Array List : [Geeks, For, Geeks]
The Linked Hash Set : [Geeks, For]
Approach 3
Using this approach, we iterate over the ArrayList and in each iteration fill the LinkedHashSet with the value using the predefined add() method of the LinkedHashSet class.
Syntax:
Hash_Set.add(Object element)
Parameters: The parameter element is of the type LinkedHashSet and refers to the element to be added to the Set.
Return Value: The function returns True if the element is not present in the LinkedHashSet otherwise False if the element is already present in the LinkedHashSet.
Example
Java
// java program to convert ArrayList
// to LinkedHashSet
// importing the java.utils package
import java.util.*;
class GFG {
// defining the method
void arrayListToHashSet()
{
// initializing the ArrayList
ArrayList<String> arrayList = new ArrayList<>();
// filling the ArrayList with values
arrayList.add("Geeks");
arrayList.add("For");
arrayList.add("Geeks");
// printing the list
System.out.println("The Array List : " + arrayList);
// declaring the iterator
Iterator<String> itr = arrayList.iterator();
// initializing the LinkedHashSet
LinkedHashSet<String> linkedHashSet
= new LinkedHashSet<>();
// loop to iterate through the ArrayList
while (itr.hasNext())
// using the add()
// to fill the HashSet
linkedHashSet.add(itr.next());
// printing the LinkedHashSet
System.out.println("The Linked Hash Set : "
+ linkedHashSet);
}
// Driver Code
public static void main(String[] args)
{
// instantiating the class
GFG ob = new GFG();
// calling the method
ob.arrayListToHashSet();
}
}
OutputThe Array List : [Geeks, For, Geeks]
The Linked Hash Set : [Geeks, For]
Approach 4
Under this approach, we first convert the ArrayList to a stream which is then converted to a Set. This Set is finally converted to a LinkedHashSet. Stream class is only available for JDK versions 8 or above.
Example
Java
// java program to convert ArrayList
// to LinkedHashSet
import java.util.*;
import java.util.stream.*;
class GFG {
// defining the method
void arrayListToLinkedHashSet()
{
// initializing the ArrayList
ArrayList<String> arrayList = new ArrayList<>();
// filling the ArrayList with values
arrayList.add("Geeks");
arrayList.add("For");
arrayList.add("Geeks");
// printing the list
System.out.println("The Array List : " + arrayList);
// creating a stream from the ArrayList
Stream<String> stream = arrayList.stream();
// creating a set from the Stream
// using the predefined toSet()
// method of the Collectors class
Set<String> set
= stream.collect(Collectors.toSet());
// converting the Set to
// LinkedHashSet
LinkedHashSet<String> linkedHashSet
= new LinkedHashSet<>(set);
// printing the LinkedHashSet
System.out.println("The Linked Hash Set : "
+ linkedHashSet);
}
// Driver Code
public static void main(String[] args)
{
// instantiating the class
GFG ob = new GFG();
// calling the method
ob.arrayListToLinkedHashSet();
}
}
OutputThe Array List : [Geeks, For, Geeks]
The Linked Hash Set : [Geeks, For]
Converting ArrayList Of Custom Class Objects To LinkedHashSet
The above examples illustrate the procedure to convert ArrayList of primitive data types such as Integer, String, and so on. Here, we are going to use the above approaches to convert an ArrayList of custom class objects to LinkedHashSet. An interesting feature of the conversion is that this allows duplication of objects which was not allowed in the above scenarios. The reason for the same being that each time a new object of the same class is created and the equals() method which is used to check elements before entering them in the set when compares the objects, finds unique references since each new object holds a new reference. This allows for the same data to be present in the LinkedHashSet in more than one places.
Example
Java
// java code to convert an ArrayList
// of custom class objects to
// LinkedHashSet
// importing the libraries
import java.util.*;
// the custom class
class Sports {
// global variable name of type String
// to hold the name of the sport
private String name;
// constructor
public Sports(String name)
{
// initializing the name
this.name = name;
}
// method to return the string
public String returnString()
{
return name + " is a great sport";
}
}
// primary class
class GFG {
// declaring the method
static void arrayListToLinkedHashSet()
{
// creating an array list of type
// class Sports
ArrayList<Sports> listOfSports
= new ArrayList<Sports>();
// adding the new instances of Sports
// in the array list
listOfSports.add(new Sports("Football"));
listOfSports.add(new Sports("Basketball"));
listOfSports.add(new Sports("Football"));
// printing the list
System.out.println("The Array List : "
+ listOfSports);
// declaring an iterator of type Sports
// to iterate over the list
Iterator<Sports> itr = listOfSports.iterator();
// iterating over the list
while (itr.hasNext())
// printing the contents
// by calling the returnString()
System.out.println(itr.next().returnString());
// initializing the linkedhashset
// of type Sports
LinkedHashSet<Sports> linkedHashSet
= new LinkedHashSet<Sports>(listOfSports);
// printing the contents of the
// linked hash set
System.out.println("The Linked Hash Set : "
+ linkedHashSet);
// declaring an iterator to iterate
// over linkedhashset
Iterator<Sports> itr1 = linkedHashSet.iterator();
// iterating over the linkedhashset
while (itr1.hasNext()) {
// calling the returnString()
// of Sports
System.out.println(itr1.next().returnString());
}
}
// Driver Code
public static void main(String[] args)
{
// calling the method
arrayListToLinkedHashSet();
}
}
OutputThe Array List : [Sports@4e50df2e, Sports@1d81eb93, Sports@7291c18f]
Football is a great sport
Basketball is a great sport
Football is a great sport
The Linked Hash Set : [Sports@4e50df2e, Sports@1d81eb93, Sports@7291c18f]
Football is a great sport
Basketball is a great sport
Football is a great sport
Explanation:
In the first line, the contents of ArrayList are printed which as can be seen are references to class Sports. In the following three lines, the contents of the returnString() method of Sports class are printed. It should be noted that all references are unique and hence the LinkedHashSet allows them even though the contents might be the same. In the following line, the contents of LinkedHashSet is printed which are again references to the class Sports. The lines following that are the returnString() method calls.
Similar Reads
Java Tutorial
Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts
Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers
Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java
Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java
Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java
Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling
Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc.An Exception is an unwanted or unexpected event that occurs during the execution of a program (i.e., at runti
10 min read
Steady State Response
In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read