Friday 13 January 2012

How to convert ArrayList to Set in Java with 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 keep insertion order
and guarantees 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 sometime size of ArrayList doesn't match with size of HashSet after conversion. Converting ArrayList to Set is entirely different than Converting Map to List but has one thing common , A constructor which takes a collection object. HashSet also has a constructor which takes another collection object e.g. ArrayList and creates Set out of those element. we have also seen a bit of this on 10 Examples of ArrayList in Java and we will see here in detail.


How to Convert List to Set in Java

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 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 Converstion: " + companies.size());
        System.out.println(companies);
     
        //Converting ArrayList into HashSet in Java
        HashSet companySet = new HashSet(companies);
     
        System.out.println("Size of HashSet after Converstion: " + companies.size());
        System.out.println(companySet);
 
    }
}

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


You might have noticed that Size of Converted ArrayList cum HashSet is not same and one less than 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 than copy it back into ArrayList you  don't have duplicates anymore.

That’s all on quick tip to Convert an ArrayList into HashSet in Java. You may check difference between ArrayList and Vector to know more about ArrayList and other Collection class.

No comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More