生成不同集合的组合

时间:2018-06-22 07:33:30

标签: java guava

我有3个相同对象的集合,但是每个对象都有一个类型属性,例如枚举。

每个集合的Objects具有相同的type属性。 因此,设置1的所有Objects属性都与type属性不同,其他所有属性都相同。

现在,我想将这3个集合都具有所有组合,例如,结果集需要有1个set1、2个set2和1个set3(这是可配置的)。

所以我试图将这3套合并为一组,并使用google guava Sets.combinations(bigSet,4)来获取那些大小为4的所有组合。之后,我将滤除那些不能满足那些规则。

我担心这不是最有效的方法。因为首先该方法生成更多组合,然后我才需要,然后我需要过滤3次(每组1次)以删除没有正确数量的类型对象的组。因此,如果将来需要额外的设置,则需要过滤4次。

是否有更好的方法来生成这些集合?

虚拟课:

public class Dummy {
    String name;
    Type type;

    public Dummy(String name, Type type) {
        this.name = name;
        this.type = type;
    }

    @Override
    public String toString() {
        return "Dummy{" +
                "name='" + name + '\'' +
                ", type=" + type +
                '}';
    }
}

测试代码:

    Dummy d1 = new Dummy("Rik", Type.TYPE1);

    Dummy d2 = new Dummy("John", Type.TYPE2);
    Dummy d3 = new Dummy("Bart", Type.TYPE2);

    Dummy d4 = new Dummy("Elisabeth", Type.TYPE3);
    Dummy d5 = new Dummy("Annie", Type.TYPE3);

    Set<Dummy> dummySet1 = ImmutableSet.of(d1);
    Set<Dummy> dummySet2 = ImmutableSet.of(d2, d3);
    Set<Dummy> dummySet3 = ImmutableSet.of(d4, d5);;

    Set<Dummy> result = new HashSet<Dummy>();
    result.addAll(dummySet1);
    result.addAll(dummySet2);
    result.addAll(dummySet3);
    System.out.println(result);

    Set<Set<Dummy>> combinations = Sets.combinations(result, 4);

    Set<Set<Dummy>> endResult = new HashSet<>();
    for (Set<Dummy> set : combinations) {
        long type1Count = set.stream().filter(s -> s.type == Type.TYPE1).count();
        long type2Count = set.stream().filter(s -> s.type == Type.TYPE2).count();
        long type3Count = set.stream().filter(s -> s.type == Type.TYPE3).count();

        if (type1Count == 1 && type2Count == 2 && type3Count == 1) {
            endResult.add(set);
        }
    }

    for (Set<Dummy> set : endResult) {
        System.out.println(set);
    }

1 个答案:

答案 0 :(得分:3)

请改用它,因为它不会生成无效的组合:

Sets.cartesianProduct(
   Sets.combinations(Set1, set1Count), 
   Sets.combinations(Set2, set2Count), 
   Sets.combinations(Set3, set3Count));