我需要一个java函数,它转换java.util.List
为java.util.Set
,反之亦然,独立于对象的类型List/Set
.
java集合框架的大多数类都有一个构造函数,它将元素集合作为参数.您应该使用您喜欢的实现吨来进行exameple的转换(带HashSet
和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);
}
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)