Convert Java Set to Java List

Convert Java Set to List

In this article, we will go through 4 different ways to convert java Set to Java List object.
Java Set Object
mySet is the Set object which contains 4 Strings.
Set  mySet = new HashSet(Arrays.asList("Red", "Yellow", "Green", "Blue"));
Using Constructor
List  myList = new ArrayList(mySet);
Using addAll
Using the addAll method we can add all the items in the set to list-objects.
List  myList2 = new ArrayList();
Using for each
By using for each to loop though all the items in the Set we can add them one by one to the List.
List  myList3 = new ArrayList();
Using Java Stream
List  myList4 =;
Full source code

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

public class JavaListFromSet {

	public static void main(String[] args) {
		Set<String> mySet = new HashSet<String>(Arrays.asList("Red", "Yellow", "Green", "Blue"));

		// Using Constructor
		List<String> myList = new ArrayList<String>(mySet);
		myList.forEach(a -> System.out.println(a));

		// Using addAll
		List<String> myList2 = new ArrayList<String>();
		myList2.forEach(a -> System.out.println(a));

		// Using For Each
		List<String> myList3 = new ArrayList<String>();
		mySet.forEach(a -> myList3.add(a));
		myList3.forEach(a -> System.out.println(a));

		// Using Stream
		List<String> myList4 =;
		myList4.forEach(a -> System.out.println(a));


No comments :

Post a Comment

Please leave your message queries or suggetions.