Jim
Jim

Reputation: 19582

Initialize a hashmap in a more compact way without external libraries

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

Upvotes: 4

Views: 286

Answers (2)

rolfl
rolfl

Reputation: 17707

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

Upvotes: 6

Antot
Antot

Reputation: 3964

There is a way to make it more compact:

Map<Integer, CustomType> typeMappings2 = new HashMap<Integer, CustomType>() {{
    put(513, CustomType.TYPE_A);
    put(520, CustomType.TYPE_A);
    put(528, CustomType.TYPE_A);
    put(530, CustomType.TYPE_A);
    put(532, CustomType.TYPE_A);
    put(501, CustomType.TYPE_B);
    put(519, CustomType.TYPE_B);
    put(529, CustomType.TYPE_B);
}};

... but aesthetically it is not very beautiful either.

Upvotes: 1

Related Questions