sneppets-java8

How to Convert Set to List (HashSet to ArrayList)

This tutorial shows you how to convert Set to List in Java using different ways.

Convert Set to List Example

package com.sneppets.example;

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

public class ConvertSetToListExample {
	
	public static void main(String[] args) {
		
		System.out.println("Set elements..");
		Set<String> hashSet = new HashSet<>();
		hashSet.add("a");
		hashSet.add("b");
		hashSet.add("c");
		hashSet.add("d");
		
		for(String str : hashSet) {
			System.out.println(str);
		}
		
		System.out.println("Convert Set to List....");
		System.out.println("Method 1: ArrayList Constructor");
		//Using ArrayList constructor
		List<String> list = new ArrayList<>(hashSet);		
		printList(list);
		
		System.out.println("Method 2: Java 8 Stream");
		//Using Java 8
		List<String> listJava8 = hashSet.stream().collect(Collectors.toList());
		printList(listJava8);	
		
	}

	private static void printList(List<String> list) {
		
		for(String str : list) {
			System.out.println(str);
		}
		
	}

}

Ouput

Set elements..
a
b
c
d
Convert Set to List....
Method 1: ArrayList Constructor
a
b
c
d
Method 2: Java 8 Stream
a
b
c
d

1. Constructor

You can make use to ArrayList constructor ArrayList(Collection<? extends E> c) which can be used to construct list containing the elements of specified collection as an argument.

List<String> list = new ArrayList<>(hashSet);

2. Java 8 Stream

Using Java 8, you can make use of Stream API to convert a Set to List by performing collect operation on the stream and then use Collectors.toList() to accumulate elements into a List as shown.

List<String> listJava8 = hashSet.stream().collect(Collectors.toList());

3. Other Libraries

There are other libraries and utils available to perform this conversion like Guava and  oracle.javatools.util.ImmutableList<E>

3.1 Guava’s Lists.newArrayList()

//Method to convert set to list
public List<String> convertToList(Set<String> set)
{
	return Lists.newArrayList(set);
}

3.2 ImmutableList.copyOf()

//Method to convert set to list
public List<String> convertToList(Set<String> set)
{
	return ImmutableList.copyOf(set);
}

Also See

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments