DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong

Trending

  • Moving 900+ GB of Prometheus Without a Cutover Weekend
  • When RabbitMQ Accepts a Message but Does Not Route It to a Queue
  • To Switch, or Not to Switch the AI Model
  • Treat Salesforce Configuration Like Code: Release Discipline in a Copado Pipeline

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Java: Create a Map With Predefined Keys

Java: Create a Map With Predefined Keys

By 
Taha Dalal
·
Jan. 27, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
24.5K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Jackson Annotations for JSON (Part 1): Serialization and Deserialization.
  • The Best of Java Collections [Tutorials].
Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook