Declare and Put String array in HashMap in one step

15,494

Solution 1

This will do it:

instruments.put("EURUSD", new String[]{"4001","EURUSD","10000","0.00001","0.1","USD"});

Solution 2

To get it all in one sentence, use double-braces initialization: -

 HashMap<String,String[]> instruments = new HashMap<String, String[]>() {
     {
      put("EURUSD", new String[]{"4001","EURUSD","10000","0.00001","0.1","USD"});
      put("EUR", new String[]{"4001","EURUSD","10000","0.00001","0.1","USD"});
     }
 };

Solution 3

I think you already got what works. But the reason that

instruments.put("EURUSD", {"4001","EURUSD","10000","0.00001","0.1","USD"});

doesn't work is because {"4001","EURUSD","10000","0.00001","0.1","USD"}. {} is a syntactic sugar or short-cut in Java array for initialization. It comes with a constraint that it always has to go along with the array declaration statement, otherwise it's a syntax error.

Array declaration statement like

String[] array = {"1", "2"};

That way Java knows that the array that it needs to create for you is actually of String type elements.

If you break the above statement as follows

String[] array;
array = {"1", "2"};

It doesn't compile.

And with the new String[]{"4001","EURUSD","10000","0.00001","0.1","USD"}, the compiler knows that it has to instantiate a new array which element type is String (new String[]) and initialize the newly instantiated array with values you provided ({"4001","EURUSD","10000","0.00001","0.1","USD"}).

Share:
15,494
jule64
Author by

jule64

Updated on June 18, 2022

Comments

  • jule64
    jule64 almost 2 years

    I am trying to insert static data into a HashMap in Java like this:

    HashMap<String,String[]> instruments = new HashMap<String, String[]>();
    instruments.put("EURUSD", {"4001","EURUSD","10000","0.00001","0.1","USD"});
    

    But the compiler doesn't like it. The only way I found to insert that data into the HashMap is to declare the string array separately and then put it into the HashMap, like this

    String[] instruDetails = {"4001","EURUSD","10000","0.00001","0.1","USD"};
    instruments.put("EURUSD", instruDetails);
    

    But it not very expressive, and hard to maintain

    So my question is, is there a way to do the put() operation and string array declaration in one step/line?