Thursday, September 14, 2023

How to convert a List to Set in Java? ArrayList to HashSet Example

Converting ArrayList to Set in Java means creating a Set implementation like HashSet from an ArrayList full of objects. Before Converting your ArrayList into HashSet do remember that List keeps insertion order and guarantees the same but Set doesn't have such obligation. Also, List allows duplicates but Set doesn't allow any duplicates, which means if you have duplicates in your ArrayList they will be lost when you convert ArrayList to HashSet and that's the reason why the sometimes size of ArrayList doesn't match with the size of HashSet after conversion.


Converting ArrayList to Set is entirely different than Converting Map to List but has one thing in common, A constructor that takes a collection object. HashSet also has a constructor that takes another collection object e.g. ArrayList and creates Set out of those elements. 

We have also seen a bit of this on 10 Examples of ArrayList in Java and we will see here in detail.

And, If you are new to the Java world then I also recommend you go through these Java Collection Courses to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.

Update: From JDK 8 onwards you can also use Stream to convert a List to Set in Java. For example, you can first convert List into Stream by using stream() method and then collect the stream elements into a Set using collect() method. Although its a bit involved you can use this to convert one Collection to another in Java like an ArrayList to HashSet and vice-versa. 



How to Convert a List to Set in Java? Step by Step Example

Now, let's  see a couple of ways to convert a List to Set like HashSet in Java :

1. ArrayList to Set Conversion Example

Converting ArrayList or any other List implementation into HashSet or any other Set Implementation is not very difficult to write. In this Java tutorial, we will see a complete code example of converting ArrayList to HashSet in Java:


package test;

import java.util.ArrayList;
import java.util.HashSet;

public class ArrayListToSetConverter {

    public static void main(String args[]){
      
        //Creating ArrayList for converting into HashSet
        ArrayList companies = new ArrayList();
        companies.add("Sony");
        companies.add("Samsung");
        companies.add("Microsoft");
        companies.add("Intel");
        companies.add("Sony");
      
        System.out.println("Size of ArrayList before Conversion: " + companies.size());
        System.out.println(companies);
      
        //Converting ArrayList into HashSet in Java
        HashSet companySet = new HashSet(companies);
      
        System.out.println("Size of HashSet after Conversion: " + companies.size());
        System.out.println(companySet);
  
    }
}

Output:
Size of ArrayList before Conversation: 5
[Sony, Samsung, Microsoft, Intel, Sony]
Size of HashSet after Conversation: 5
[Sony, Microsoft, Intel, Samsung]


You might have noticed that the Size of the Converted ArrayList cum HashSet is not the same and one less than the original  ArrayList because duplicate entry "Sony" is just one time in Set. 

This is another great way of removing duplicates from ArrayList. just copy entries of ArrayList into Set and then copy it back into ArrayList you don't have duplicates anymore.

How to convert ArrayList to Set in Java? Example


That’s all on the quick tip to Convert an ArrayList into HashSet in Java. You may check the difference between ArrayList and Vector to know more about ArrayList and other Collection classes. You can use this trick to also convert one Collection to another in Java. 

As long as the class implements Collection interface, you can use the copy constructor to copy elements from one Collection to other and convert one collection to other in Java. 


Related Java Tutorial

Also, what is your favorite way to convert an ArrayList to HashSet in Java? By using  copy constructor of Collection class or Stream and collect() method combo or anything else? Do let me know in comments. 

6 comments:

  1. Size of HashSet after Converstion should be 4 if i am not mistaken.please correct me if i am wrong.
    thanks

    ReplyDelete
  2. @Anonymous you are absolutely correct, Size must be four its a bug if you see carefully I am still printing size of list instead of size of hashset in Java.
    companies.size() //size of list.
    will correct it. thanks for pointing it out.

    ReplyDelete
  3. ArrayList to HashSet conversion is my most preferred method to remove duplicates from collection if Insertion order is not concern, as insertion order gets lost when you copy elements form ArrayList to HashSet. if you still wants to use HashSet to remove duplicates and want to keep the insertion order of List than consider using LinkedHashSet.

    ReplyDelete
  4. It's 4 if he printing companySet.size(). However, I think there is a typo still printing companies.size() which is 5

    ReplyDelete
  5. Adding more - Its always a great idea to check the list for null(if list is returned by a method or list items are supplied from another object), else you will encounter NPE while creating the HashSet instance.

    ReplyDelete
  6. how to implement set using list ? Set shouldn't be used.

    ReplyDelete