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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones Build AI Agents That Are Ready for Production
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
Build AI Agents That Are Ready for Production

LIVE: “Cognitive Databases, Intelligent Data: Unified Infrastructure for Vector Search, AI-Optimized Queries, & Hybrid Workloads" Report

Join this live webinar to learn safer rollout techniques for schema changes, index testing, and database migrations.

Live Webinar: Exclusive practitioner summit on AI-powered CDN operations and real-world automation strategies

Related

  • Jakarta NoSQL: Why JPA Is Not Enough for the AI Era
  • Top Java Security Vulnerabilities and How to Prevent Them in Modern Java
  • A Spring Boot App With Half the Startup Time
  • Implementing the Planning Pattern With Java Enterprise and LangChain4j

Trending

  • Building AI-Powered Java Applications With Jakarta EE and LangChain4j
  • Jakarta NoSQL: Why JPA Is Not Enough for the AI Era
  • Orchestrating Zero-Downtime Deployments With Temporal
  • LLM Agents and Getting Started with Them
  1. DZone
  2. Coding
  3. Java
  4. Java: Create a Map With Predefined Keys

Java: Create a Map With Predefined Keys

By 
Taha Dalal user avatar
Taha Dalal
·
Jan. 27, 20 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
24.3K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • Jakarta NoSQL: Why JPA Is Not Enough for the AI Era
  • Top Java Security Vulnerabilities and How to Prevent Them in Modern Java
  • A Spring Boot App With Half the Startup Time
  • Implementing the Planning Pattern With Java Enterprise and LangChain4j

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • 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