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,328
  • 2
  • 25
  • 24
Shreyash Mahajan
  • 23,386
  • 35
  • 116
  • 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
  • 588,226
  • 146
  • 1,060
  • 1,140
4

Use a static block:

static {
  mediaListWithCategory.put(youKey, yourValue);
}
ewan.chalmers
  • 16,145
  • 43
  • 60
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
  • 64,482
  • 16
  • 119
  • 213