Is there a way to make this code more compact? With less lines without using libraries?
I am using Java 7
public enum CustomType {
TYPE_A,
TYPE_B,
TYPE_C,
}
private static final Map<Integer, CustomType> typeMappings = new HashMap<>();
static {
typeMappings.put(513, CustomType.TYPE_A);
typeMappings.put(520, CustomType.TYPE_A);
typeMappings.put(528, CustomType.TYPE_A);
typeMappings.put(530, CustomType.TYPE_A);
typeMappings.put(532, CustomType.TYPE_A);
typeMappings.put(501, CustomType.TYPE_B);
typeMappings.put(519, CustomType.TYPE_B);
typeMappings.put(529, CustomType.TYPE_B);
}
Assuming that you have full control over both the mapping, and the enum classes, then the more traditional way to solve this problem is to embed the mapping in to the enums.
public enum CustomType {
TYPE_A(513, 520, 528, 530, 532),
TYPE_B(501, 519, 529),
TYPE_C();
private static final Map<Integer, CustomType> typeMappings = new HashMap<>();
static {
for (CustomType ct : values()) {
for (int v : ct.mapto) {
typeMappings.put(v, ct);
}
}
}
private final int mapto[];
CustomType(int ... mapto) {
this.mapto = mapto;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With