EN
Java - create and initialize Map<> simultaneously
4
points
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");
}
}