{{announcement.body}}
{{announcement.title}}

Java: Create a Map With Predefined Keys

DZone 's Guide to

Java: Create a Map With Predefined Keys

In this article, we discuss how to use Lombok, Jackson, and enums to create a Map from a set of predefined keys.

· Java Zone ·
Free Resource

This 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 :

Java




xxxxxxxxxx
1


 
1
@Builder
2
@Getter
3
class ClassWithPredefinedKeys {
4
    private String prop1;
5
    private String prop2;   
6
}


  

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:

Java




x


1
ClassWithPredefinedKeys builder 
2
    = ClassWithPredefinedKeys
3
        .builder()
4
            .prop1("value3")
5
            .prop2("value4")
6
        .build();
7
        
8
ObjectMapper mapper = new ObjectMapper();
9
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 :

Java




x


1
@Builder
2
class ClassWithKeysInEnum {
3
    
4
    public enum Properties {
5
        prop1,
6
        prop2
7
    }
8
    
9
    @Singular
10
    private Map<Properties,String> properties;
11
    
12
    public Map<String, String> getProperties(){
13
        Map<String, String> stringProperties = new HashMap<String, String>();
14
        this.properties.forEach((key,value) -> {
15
            stringProperties.put(key.toString(), value);
16
        });
17
        return stringProperties;
18
    }
19
    
20
}



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 :

Java




x


 
1
System.out.println(
2
    ClassWithKeysInEnum
3
        .builder()
4
            .property(Properties.prop1, "value1")
5
            .property(Properties.prop2, "value2")
6
        .build()
7
        .getProperties()
8
);




Further Reading

Topics:
lombok ,jackson ,java ,map ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}