Is Arrays.asList also for maps?

I have the code below:

Map<String, Map<Double, String>> map = new HashMap<>(); Map<Double,String> Amap = new HashMap<>(); map.put(getValuesTypes.FUT(), HERE); 

Instead of first creating a map and putting it in "HERE", I am looking for a function that I could use with List there Arrays.asList(...) so that I can simply enter "Here" ?.asMap({1.0,"A"}, {2.0,"B"})

+5
source share
5 answers

You can initialize the HashMap as follows.

 new HashMap<Double, String>() { { put(1.0, "ValA"); put(2.0, "ValB"); } }; 
+6
source

With guava

 Map<Double, String> map = ImmutableMap.of(1.0, "A", 2.0, "B"); 
+3
source

There is no literal to initialize the map in this way. But you can use an anonymous class created in place:

 map.put(getValuesTypes.FUT(), new HashMap<Double, String>() {{ put(1.0, "A"); put(2.0, "B"); }}); 

although this is not recommended. I would suggest using Guava ImmutableMap :

 map.put(getValuesTypes.FUT(), ImmutableMap.<Double, String>of(1.0, "A", 2.0, "B")); 

If the number of pairs is greater than 5 , you should use their builder :

 map.put(getValuesTypes.FUT(), ImmutableMap.<Double, String>builder().put(1.0, "A")/* 5+ puts */.build()); 
+1
source

Guava ImmutableMap.of (..) can help in this direction:

 ImmutableMap.of(1, "a"); 

only Collections.singletonMap (..) exists in the JDK, but this only gives you a map with a single pair.

There was a discussion in the guava project to contain Maps.asMap(Object... varArgs) , the bit was stopped. So ImmutableMap.of (...) is the way to go.

+1
source

You can only initialize a new map using an anonymous class. i.e.

new HashMap<K, V>() {{ put(key, value); put(key, value); }};

0
source

Source: https://habr.com/ru/post/1259365/


All Articles