How do I convert Set into List?

The code below gives you an example of converting a java.util.Set into a java.util.List. It has simply done by creating a new instance of List and pass the Set as the argument of the constructor.

package org.kodejava.util;

import java.util.*;

public class SetToList {
    public static void main(String[] args) {
        // Create a Set and add some objects into the Set.
        Set<Object> set = new HashSet<>();
        set.add("A");
        set.add(10L);
        set.add(new Date());

        // Convert the Set to a List can be done by passing the Set instance into
        // the constructor of a List implementation class such as ArrayList.
        List<Object> list = new ArrayList<>(set);
        for (Object o : list) {
            System.out.println("Object = " + o);
        }
    }
}

The output of the code snippet are:

Object = A
Object = 10
Object = Mon Oct 04 20:20:26 CST 2021
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.