我需要一个java函数,它从java.util.List
转换为java.util.Set
,反之亦然,与List/Set
的对象类型无关。
喜欢List.addAll
和Set.addAll
?
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);
}
}
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
}
Instead of one function you can have two function to implement this functionality:
// Set to List
public List setToList(Set set) {
return new ArrayList(set);
}
// List to Set
public Set listToSet(List list) {
return new HashSet(list);
}
In a single function:
public Collection convertSetList(Collection obj) {
if (obj instanceof java.util.List) {
return new HashSet((List)obj);
} else if(obj instanceof java.util.Set) {
return new ArrayList((Set)obj);
}
return null;
}
Example: (updated)
public class Main {
public static void main(String[] args) {
Set s = new HashSet();
List l = new ArrayList();
s.add("1");s.add("2");s.add("3");
l.add("a");l.add("b");l.add("c");
Collection c1 = convertSetList(s);
Collection c2 = convertSetList(l);
System.out.println("c1 type is : "+ c1.getClass());
System.out.println("c2 type is : "+ c2.getClass());
}
public static Collection convertSetList(Collection obj) {
if (obj instanceof java.util.List) {
System.out.println("List!");
return (Set)new HashSet((List) obj);
} else if (obj instanceof java.util.Set) {
System.out.println("Set!");
return (List)new ArrayList((Set) obj);
} else {
System.out.println("Unknow type!");
return null;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.