Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Generic List to Set conversion and vice versa

I Need a java function which converts from java.util.List to java.util.Set and vice versa, independent of type of objects in the List/Set.

like image 242
Arjun Avatar asked Mar 16 '11 08:03

Arjun


2 Answers

Most of the class of the java collection framework have a constructor that take a collection of element as a parameter. You should use your prefered implementation ton do the conversion for exameple (with HashSet and ArrayList):

public class MyCollecUtils {

    public static <E> Set<E> toSet(List<E> l) {
        return new HashSet<E>(l);
    }

    public static <E> List<E> toSet(Set<E> s) {
        return new ArrayList<E>(s);
    }
}
like image 69
Nicolas Avatar answered Sep 19 '22 16:09

Nicolas


public static <E> Set<E> getSetForList(List<E> lst){
  return new HashSet<E>(lst);//assuming you don't care for duplicate entry scenario :)
}

public static <E> List<E> getListForSet(Set<E> set){
  return new ArrayList<E>(set);// You can select any implementation of List depending on your scenario
}
like image 29
jmj Avatar answered Sep 19 '22 16:09

jmj