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
import java.util.*;
class GFG {
void arrayListToLinkedHashSet()
{
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add( "Geeks" );
arrayList.add( "For" );
arrayList.add( "Geeks" );
System.out.println( "The array list : " + arrayList);
LinkedHashSet<String> linkedHashSet
= new LinkedHashSet<String>(arrayList);
System.out.println( "The converted "
+ "Linked Hash Set : "
+ linkedHashSet);
}
public static void main(String[] args)
{
GFG ob = new GFG();
ob.arrayListToLinkedHashSet();
}
}
|
Output
The 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
import java.util.*;
class GFG {
void arrayListToLinkedHashSet()
{
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add( "Geeks" );
arrayList.add( "For" );
arrayList.add( "Geeks" );
System.out.println( "The Array List : " + arrayList);
LinkedHashSet<String> linkedHashSet
= new LinkedHashSet<>();
linkedHashSet.addAll(arrayList);
System.out.println( "The Linked "
+ "Hash Set : " + linkedHashSet);
}
public static void main(String[] args)
{
GFG ob = new GFG();
ob.arrayListToLinkedHashSet();
}
}
|
Output
The 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
import java.util.*;
class GFG {
void arrayListToHashSet()
{
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add( "Geeks" );
arrayList.add( "For" );
arrayList.add( "Geeks" );
System.out.println( "The Array List : " + arrayList);
Iterator<String> itr = arrayList.iterator();
LinkedHashSet<String> linkedHashSet
= new LinkedHashSet<>();
while (itr.hasNext())
linkedHashSet.add(itr.next());
System.out.println( "The Linked Hash Set : "
+ linkedHashSet);
}
public static void main(String[] args)
{
GFG ob = new GFG();
ob.arrayListToHashSet();
}
}
|
Output
The 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
import java.util.*;
import java.util.stream.*;
class GFG {
void arrayListToLinkedHashSet()
{
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add( "Geeks" );
arrayList.add( "For" );
arrayList.add( "Geeks" );
System.out.println( "The Array List : " + arrayList);
Stream<String> stream = arrayList.stream();
Set<String> set
= stream.collect(Collectors.toSet());
LinkedHashSet<String> linkedHashSet
= new LinkedHashSet<>(set);
System.out.println( "The Linked Hash Set : "
+ linkedHashSet);
}
public static void main(String[] args)
{
GFG ob = new GFG();
ob.arrayListToLinkedHashSet();
}
}
|
Output
The 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
import java.util.*;
class Sports {
private String name;
public Sports(String name)
{
this .name = name;
}
public String returnString()
{
return name + " is a great sport" ;
}
}
class GFG {
static void arrayListToLinkedHashSet()
{
ArrayList<Sports> listOfSports
= new ArrayList<Sports>();
listOfSports.add( new Sports( "Football" ));
listOfSports.add( new Sports( "Basketball" ));
listOfSports.add( new Sports( "Football" ));
System.out.println( "The Array List : "
+ listOfSports);
Iterator<Sports> itr = listOfSports.iterator();
while (itr.hasNext())
System.out.println(itr.next().returnString());
LinkedHashSet<Sports> linkedHashSet
= new LinkedHashSet<Sports>(listOfSports);
System.out.println( "The Linked Hash Set : "
+ linkedHashSet);
Iterator<Sports> itr1 = linkedHashSet.iterator();
while (itr1.hasNext()) {
System.out.println(itr1.next().returnString());
}
}
public static void main(String[] args)
{
arrayListToLinkedHashSet();
}
}
|
Output
The 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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...