How to convert List of data to Set of data and vice versa in Java?

UPDATED: 07 October 2016
Following excerpt shows how you can convert List<T> to Set<T> and Set<T> to List<T> in java.

Source code (ListToSet.java)
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * List to Set example.
 *
 * @author javaQuery
 * @date 7th October, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class ListToSet {

    public static void main(String[] args) {
        /* Create list of string */
        List<String> strings = new ArrayList<String>();
        strings.add("A");
        strings.add("B");

        Set<String> stringSet = new HashSet<String>(strings);
        /**
         * new HashSet(Collection<? extends E> c) 
         * We created Set of String so we can initialize HashSet using any collection that extends String.
         */
        
        for (String string : stringSet) {
            System.out.println(string);
        }
    }
}
You would like to read How to Initialize List in declaration?.

Source code (SetToList.java)
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Set to List example.
 *
 * @author javaQuery
 * @date 7th October, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class SetToList {

    public static void main(String[] args) {
        /* Create set of string */
        Set<String> strings = new HashSet<String>();
        strings.add("A");
        strings.add("B");

        List<String> list = new ArrayList<>(strings);
        /**
         * new ArrayList(Collection<? extends E> c) 
         * We created List of String so we can initialize ArrayList using any collection that extends String.
         */
        
        for (String string : list) {
            System.out.println(string);
        }
    }
}
You would like to read How to Initialize Set in declaration?.

Output
A
B

0 comments :