java-Ways to create and initialize java HashMap inline
1. The purpose of this post
I would demo how to create and initialize java HashMap inline by different methods.
2. Environments
- java 1.8+
- Vavr 0.9+
- Guava 25.0+
3. Ways to create and initialize java HashMap inline
3.1 For jdk versions less or equal to java 8
3.1.1 The imperative way
The most imperative way to create a java HashMap is:
3.1.2 The anonymous class
Use Anonymous Subclass to Initialize a HashMap This creates an anonymous subclass of HashMap, whose instance initializer puts these values. In other words it creates a new class that inherits from HashMap. This is the shortest way to create and initialize a dynamic HashMap
3.2 For Java Version 9 or higher
3.2.1 Use Map.of to create immutable map inline
the Map.of method is defined for up to ten elements in the map, while the Map.ofEntries method will have no such limit.
The return type is unmodifiable, if you want to make it modifiable.
3.2.2 Use Map.ofEntries to create immutable map inline
The return type is unmodifiable, if you want to make it modifiable.
3.3 Use library: Vavr
According to the Vavr’s website:
Vavr is an object-functional language extension to Java 8, which aims to reduce the lines of code and increase code quality. It provides persistent collections, functional abstractions for error handling, concurrent programming, pattern matching and much more.
Because Vavr does not depend on any libraries (other than the JVM) you can easily add it as standalone .jar to your classpath.
First, add the vavr dependency to your pom:
Then ,use the Guava’s HashMap to create and initialize the Map:
The toJavaMap would return a modifiable HashMap.
3.4 Use library: Guava
Guava is a set of core libraries that includes new collection types (such as multimap and multiset), immutable collections, a graph library, functional types, an in-memory cache, and APIs/utilities for concurrency, I/O, hashing, primitives, reflection, string processing, and much more!
First,add Guava to your pom:
Then, use the Guava’s ImmutableMap.of to create and initialize the Map:
4. Summary
Create and initialize a java HashMap is easy by using libraries,but you can still just use the jdk way to do this job.