Converting ArrayList
to Setin Java
means creating a Set implementation like HashSet from an ArrayListfull
of objects.Before Converting yourArrayList into
hashSet
do remember thatList keep insertion order and guarantees same but Set doesn't have such obligation. Also List allowsduplicates but Set doesn't
a
llow 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 acollection 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
![How to convert List to Set in Java Example](http://2.bp.blogspot.com/-wrzDeQGAe1I/TWu8pLuLr4I/AAAAAAAAADE/V017G-6Q61w/s1600/java_logo_50_50.jpg)
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 ArrayListbecause 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 maycheck difference between ArrayList and Vector to know more about ArrayList and other Collection class.
Read more: http://javarevisited.blogspot.com/2012/01/convert-arraylist-to-set-java-example.html#ixzz2kheYNB9i