How to Convert ArrayList to LinkedHashSet in Java? - GeeksforGeeks

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.
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 packageimport 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();    }}
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
// java program to convert ArrayList// to LinkedHashSet // importing the java.utils packageimport 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();    }}
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
// java program to convert ArrayList// to LinkedHashSet // importing the java.utils packageimport 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();    }}
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
// 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();    }}
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
// java code to convert an ArrayList// of custom class objects to// LinkedHashSet // importing the librariesimport java.util.*; // the custom classclass 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 classclass 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();    }}
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.
 
gabaa406
arorakashish0911
Java-ArrayList
java-LinkedHashSet
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java