2

Is there any shorter way of doing this?

Map<String, Integer> values = new HashMap<String, Integer>();
values.put("A", 1);
values.put("E", 1);
values.put("D", 2);
values.put("R", 2);
values.put("B", 3);
values.put("M", 3);
values.put("V", 4);
values.put("Y", 4);
values.put("J", 8);
values.put("X", 8);

With arrays in Java you can do this for example

int[] temp = {1,2};

instead of

int[] temp = new int[2]
temp[0] = 1;
temp[1] = 2;

I am looking to something similar with the Map above. Is that possible?

Thanks for the help, as always :)

herteladrian
  • 381
  • 1
  • 6
  • 18
  • have you looked at the methods present in HashMap ??.. If you are using eclipse, ctrl+space will give you your answer. – TheLostMind Jan 17 '14 at 06:51
  • I don't know what to look for in the HashMap API. Could you point me into the right direction? and I am not using eclipse @TheLostMind – herteladrian Jan 17 '14 at 06:52
  • well..If you look at the HashMap API, you wont find any method that would help you.. I would look at Peter's answer... use a loop if necessary... – TheLostMind Jan 17 '14 at 07:00

4 Answers4

4

You could try this, but you have to be careful:

HashMap<String, Integer> values = new HashMap<String, Integer>()
{
    {
        put("A", 1);
        put("E", 1);
        put("D", 2);
        put("R", 2);
        put("B", 3);
        put("M", 3);
        put("V", 4);
        put("Y", 4);
        put("J", 8);
        put("X", 8);
    }
};

Read more about Double Brace Initialization here.

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
3

There is no easier way using Java only, but if you use Guava, you could do this:

  Map<String, Integer> values = 
     ImmutableMap.<String, Integer> builder().put("A", 1).put("E", 1).put("D", 2).build();

See also:

Community
  • 1
  • 1
LaurentG
  • 11,128
  • 9
  • 51
  • 66
2

No, there's no direct way of doing this.

You need to initialize the map as you suggested.

Map<String, Integer> values = new HashMap<String, Integer>();
values.put("A", 1);
values.put("E", 1);
values.put("D", 2);
values.put("R", 2);
values.put("B", 3);
values.put("M", 3);
values.put("V", 4);
values.put("Y", 4);
values.put("J", 8);
values.put("X", 8);

If there's any pattern in these values, you can simplify that to using a loop.

An alternative is to use HashMapBuilder.

See also here.

How to directly initialize a HashMap (in a literal way)?

Another alternative is to use Guava. They have a method for this.

Community
  • 1
  • 1
peter.petrov
  • 38,363
  • 16
  • 94
  • 159
1

If you think that you know the combination of keys and values, you can do like this, but its a kind of hack :

String[] keys = {"A", "B", "C"};
int[] values = {1, 2, 3};

Map<String, Integer> myMap = new HashMap<String, Integer>();

for(int i = 0; i < keys.length; i++){
  myMap.put(keys[i], values[i]);
}

But you have to be very careful, most importantly that both your arrays should be of same length.

Abubakkar
  • 15,488
  • 8
  • 55
  • 83