Main Tutorials

How to convert List to Set (ArrayList to HashSet)

Collection object has a constructor that accept a Collection object to initial the value. Since both Set and List are extend the Collection, the conversion is quite straightforward. It’s just pass a List into Set constructor or vice verse.

Convert List to Set

Set set = new HashSet(list);
Convert Set to List

List list = new ArrayList(set);

1. List To Set Example


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ConvertListToSet
{
    public static void main( String[] args )
    {
    	System.out.println("List values .....");
    	List<String> list = new ArrayList<String>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        list.add("1");
        
        for (String temp : list){
        	System.out.println(temp);
        }
        
        Set<String> set = new HashSet<String>(list);
        
        System.out.println("Set values .....");
        for (String temp : set){
        	System.out.println(temp);
        }
    }
}

Output


List values .....
1
2
3
4
1
Set values .....
3
2
1
4

After the conversion, all the duplicated values in List will just ignore, because the Set does not allow duplicated values.

2. Set To List Example


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ConvertSetToList
{
    public static void main( String[] args )
    {
    	System.out.println("Set values .....");
        Set<String> set = new HashSet<String>();
        set.add("1");
        set.add("2");
        set.add("3");
        set.add("4");
        
        for (String temp : set){
        	System.out.println(temp);
        }
        
        System.out.println("List values .....");
    	List<String> list = new ArrayList<String>(set);
        
        for (String temp : list){
        	System.out.println(temp);
        }
    }
}

Output


Set values .....
3
2
1
4
List values .....
3
2
1
4

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
8 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Pawankumar Jajara
7 years ago

@Mkyong: Your website has been a great resource to me since college. Please include Java 8 tutorials too.

Solution with JDK 8:
List myList = mySet.stream().collect(Collectors.toList());

Anna
4 years ago

comment deleted

Ashlee
4 years ago

thanks for the info!

uh
9 years ago

Any differences of your approach with the addAll method?

renso
10 years ago

Good explanation,Thank you

kumaran
10 years ago

Nice explanation i ever seen

Bhupesh Singh Padiyar
10 years ago

List To Set Example is very help full.

tanuj pandey
11 years ago

Excellent