Java: Create a Map With Predefined Keys
Join the DZone community and get the full member experience.
Join For FreeThis article walks you through the lean ways of creating a Map with a fixed (predefined) set of keys.
Option One: Using Lombok and Jackson
In this approach, we would create a simple class. This class would have a set of predefined fields. Once the object of this class is created, we can then use Jackson to create a map from this object.
Here is the snippet of the class :
xxxxxxxxxx
class ClassWithPredefinedKeys {
private String prop1;
private String prop2;
}
We can use the Builder
annotation of Lombok to get a cleaner syntax. The Getter
annotation allows Jackson access to the values of the attributes.
You may also like: Java HashMap Implementation in a Nutshell.
Here is the snippet of the implementation:
x
ClassWithPredefinedKeys builder
= ClassWithPredefinedKeys
.builder()
.prop1("value3")
.prop2("value4")
.build();
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.convertValue(builder, Map.class));
Option Two: Using Lombok and Enum
In this option, we would use an enum to predefine the keys.
Here is a snippet of the Class :
x
class ClassWithKeysInEnum {
public enum Properties {
prop1,
prop2
}
private Map<Properties,String> properties;
public Map<String, String> getProperties(){
Map<String, String> stringProperties = new HashMap<String, String>();
this.properties.forEach((key,value) -> {
stringProperties.put(key.toString(), value);
});
return stringProperties;
}
}
The Singular
annotation also belongs to Lombok. It allows for a more readable syntax for building collections (including maps).
Here is how the Map can be created using this approach :
x
System.out.println(
ClassWithKeysInEnum
.builder()
.property(Properties.prop1, "value1")
.property(Properties.prop2, "value2")
.build()
.getProperties()
);
Further Reading
Opinions expressed by DZone contributors are their own.
Comments