Wie kann man in Java elegant Objekte erstellen bei der zwei enums miteinander kombiniert werden (3*6) Objekte?

1 Antwort

Das ist eine recht dubiose Anforderung aber mithilfe von EnumSet gut machbar:

import java.util.EnumSet;
import java.util.List;
import java.util.ArrayList;
// ...
enum A {
    A1, A2, A3
}
enum B {
    B1, B2, B3, B4, B5, B6
}

// ...
public class Data {
    public A a;
    public B b;
    public Data(A a, B b) {this.a = a; this.b = b}
}
// ...
// hier passiert die Magie!
EnumSet aSet = EnumSet.allOf(A.class);
EnumSet bSet = EnumSet.allOf(B.class);
List<Data> kombinationen = new ArrayList<>();

aSet.forEach(a -> {bSet.forEach(b -> kombinationen.add(new Data((A) a, (B) b)));})

// alternativ auch als for-Schleife schreibbar,
// leider nur mit Object
for (Object a : aSet) {
    for (Object b : bSet) {
        kombinationen.add(new Data((A) a, (B) b));
    }
}

EnumSet soll auch sehr performant sein, daher sollte performance hier kein Problem sein, zumal das ja nur einmal bei Programmstart läuft.

Woher ich das weiß:Hobby