2

I have HashMap like:

static HashMap<String,ArrayList<Media>> mediaListWithCategory=new HashMap<String,ArrayList<Media>>();

I have value like:

January:
   -Sunday
   -Monday
Februsry:
   -Saturday
   -Sunday
   -Thursday
March:
   -Monday
   -Tuesday
   -Wednesday

How can I statically assign these values when defining the hash map?

Anthony Blake
  • 5,258
  • 2
  • 24
  • 24
Shreyash Mahajan
  • 22,842
  • 35
  • 109
  • 188

3 Answers3

9

You can populate it in a static block:

static {
   map.put("January", Arrays.asList(new Media("Sunday"), new Media("Monday")));
}

(You should prefer interface to concrete classes. define your type as Map<String, List<Media>>)

Bozho
  • 572,413
  • 138
  • 1,043
  • 1,132
4

Use a static block:

static {
  mediaListWithCategory.put(youKey, yourValue);
}
sudocode
  • 15,997
  • 40
  • 59
1

A variant of this may be more succinct:

static HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>() {{
    put("January", new ArrayList<String>() {{
        add("Sunday");
        add("Monday");
      }});
    put("Februsry" /* sic. */, new ArrayList<String>() {{
        add("Saturday");
        add("Sunday");
        add("Thursday");
      }});
    put("March", new ArrayList<String>() {{
        add("Monday");
        add("Tuesday");
        add("Wednesday");
      }});
}};

See Double Brace Initialisation for discussion.

Community
  • 1
  • 1
OldCurmudgeon
  • 62,806
  • 15
  • 115
  • 208