Java Collection How to - Convert a List to a Set








Question

We would like to know how to convert a List to a Set.

Answer

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/*from  w  ww.j a  v  a2  s  .  c  o m*/
public class Main {
  public static void main(String[] args) {
    List<String> myList = new ArrayList<String>();
    myList.add("A");
    myList.add("B");
    myList.add("C");
    myList.add("D");

    Set<String> mySet = new HashSet<String>(myList);

    for (Object theFruit : mySet)
      System.out.println(theFruit);
  }
}

The code above generates the following result.