hashmap declare and initialize with values in 1 line java

https:‮ual.www//‬tturi.com
hashmap declare and initialize with values in 1 line java

In Java, you can declare and initialize a HashMap with values in a single line using the following syntax:

Map<String, String> map = new HashMap<String, String>() {{
    put("key1", "value1");
    put("key2", "value2");
    put("key3", "value3");
}};

This code creates a HashMap with keys "key1", "key2", and "key3" and values "value1", "value2", and "value3", respectively.

You can also use the diamond operator to simplify the syntax:

Map<String, String> map = new HashMap<>() {{
    put("key1", "value1");
    put("key2", "value2");
    put("key3", "value3");
}};

This code has the same effect as the previous example, but it uses the diamond operator to infer the type of the keys and values from the context.

Note that the HashMap is created using an anonymous inner class, which allows you to specify the initial values using the put() method.

For more information about HashMap and other collections in Java, you can refer to the Java documentation (https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html).

Created Time:2017-11-01 12:05:05  Author:lautturi