Languages
[Edit]
EN

Java - create and initialize Map<> simultaneously

4 points
Created by:
WGates
412

In this short article, we would like to show how to create and initialize Map<> simultaneously in Java.

Quick solution:

// import java.util.Map;
                                                            // Key    Value
Map<String, Integer> map = Map.of("a", 1, "b", 2, "c", 3);  //  a  ->  1
                                                            //  b  ->  2
                                                            //  c  ->  3

Note: Map.of() method was intoduced in Java 9.

 

Practical example

import java.util.Map;

public class Program {

    public static void main(String[] args) {

        Map<String, Boolean> map1 = Map.of("a", true, "b", false, "c", false);
        Map<String, Integer> map2 = Map.of("a", 1, "b", 2, "c", 3);
        Map<String, String>  map3 = Map.of("a", "A", "b", "B", "c", "C");
    }
}

 

See also

  1. Java - create and initialize Set<> simultaneously

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join