How to give the static value to HashMap?

社会主义新天地 提交于 2019-12-06 06:02:51

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>>)

Use a static block:

static {
  mediaListWithCategory.put(youKey, yourValue);
}
OldCurmudgeon

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!