Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a hashmap in a more compact way without external libraries

Tags:

java

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);
}
like image 627
Jim Avatar asked Mar 14 '23 16:03

Jim


1 Answers

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;
    }
}
like image 95
rolfl Avatar answered May 01 '23 06:05

rolfl