map的常用使用技巧

来源:互联网 发布:软件需求文档 编辑:程序博客网 时间:2024/06/16 20:45
向一个map中添加list或者set
if(判断这个map中是否包含有一个键值){
如果包括:
1.根据键值取出相应的list或者set
2.组装list或者set中需要的数据
3.把组装好的数据add到list或者set当中

}else{
如果不包括:
1.就新建一个list或者set
2.组装set或者list中的数据
3.把组装好的数据add到list或者set当中

}

看一个例子:

List<Map<String, String>> list2 = new ArrayList<Map<String, String>>();
  
List<Map<String, String>> list3 = new ArrayList<Map<String, String>>();
list3 = teacherList;
Map<String, String> key_id_value_tName = new HashMap<String, String>();
  for (Map<String, String> map7 : list3) {
      if (!map7.isEmpty()) {
           key_id_value_tName.put(map7.get("id"), map7.get("name"));
       }
  }
        Map<String, List<Map<String, String>>> key_xnxq_value_course = new HashMap<String, List<Map<String, String>>>();
        if (list2 != null && list2.size() > 0) {
            for (Map<String, String> tempMap : list2) {
                if (key_id_value_tName.get(tempMap.get("id")) != null) {
                    tempMap.put("teacherName"key_id_value_tName.get(tempMap.get("id")));
                }
                List<Map<String, String>> tempList11 = new ArrayList<Map<String, String>>();
                String tempKey = tempMap.get("xn") + "学年" + tempMap.get("xq");
                if (key_xnxq_value_course.containsKey(tempKey)) {
                    tempList11 = key_xnxq_value_course.get(tempKey);
                    tempList11.add(tempMap);
                    key_xnxq_value_course.put(tempKey, tempList11);
                } else {
                    tempList11.add(tempMap);
                    key_xnxq_value_course.put(tempKey, tempList11);
                }
            }
        }
标红处为技巧核心,在这里等待向list中添加的tempMap我们是提前封装好的。