24

I have the below code:

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

Instead of creating a Map first and put it at "HERE", I'm looking for a function like I could use with a List there Arrays.asList(...) so that i can just enter at "Here" ?.asMap({1.0,"A"}, {2.0,"B"})

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
PowerFlower
  • 1,619
  • 4
  • 18
  • 27
  • `{1.0,"A"}` is an object array, not a map – OneCricketeer Nov 06 '16 at 13:35
  • 1
    With Java 9, you will be able to use collection factory methods for creating immutable maps, see http://download.java.net/java/jdk9/docs/api/java/util/Map.html#of-K-V- and its variants. – Tordanik Jul 13 '17 at 16:01

5 Answers5

24

You can initialize HashMap like this.

new HashMap<Double, String>() {
    {
        put(1.0, "ValA");
        put(2.0, "ValB");
    }
};
nakano531
  • 498
  • 7
  • 13
10

With Guava

Map<Double, String> map = ImmutableMap.of(1.0, "A", 2.0, "B");
Jiri Kremser
  • 12,471
  • 7
  • 45
  • 72
6

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

ImmutableMap.of(1, "a");

in the JDK there is only Collections.singletonMap(..), but this provides you just a map with a sole pair.

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

EDIT since JDK 9

In JDK 9 there were added new methods that do the same thing: Map.of(K,V)

Olimpiu POP
  • 5,001
  • 4
  • 34
  • 49
1

There is no literal to initialize a map in that way. But you could use an anonymous class generating on the spot:

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

though it's not recommended. I would suggest to use Guava's ImmutableMap:

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

If a 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());
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • Without the need to import extra libs, you can use `java.util.Collections` like so `Collections.unmodifiableMap(myHashMapInstance)` – Jaxon Aug 15 '17 at 03:09
0

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

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

Vikram Jakhar
  • 712
  • 1
  • 5
  • 13