简体   繁体   English

Java:设置转换的通用列表,反之亦然

[英]Java: Generic List to Set conversion and vice versa

我需要一个java函数,它从java.util.List转换为java.util.Set ,反之亦然,与List/Set的对象类型无关。

喜欢List.addAllSet.addAll

Most of the class of the java collection framework have a constructor that take a collection of element as a parameter. java集合框架的大多数类都有一个构造函数,它将元素集合作为参数。 You should use your prefered implementation ton do the conversion for exameple (with HashSet and ArrayList ): 您应该使用您喜欢的实现吨进行exameple的转换(使用HashSetArrayList ):

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;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM