使用Java 1.5如何将以下列表结构转换为嵌套映射:
List<CsSectionDetail> list
至Map<Integer,Map<Integer, List<CsSectionDetail>>> map = new TreeMap<Integer, Map<Integer,List<CsSectionDetail>>>();
上面的列表包含两个键 mainTaskId 和 subTaskId ,它们应该使用 first Integer mainTaskId 和转换为上面的地图结构second Integer subTaskId 。
我已经有了一个将List<CsSectionDetail>
列表转换为map的函数,其结构为Map<Integer, List<CsSectionDetail>> map = new HashMap<Integer, List<CsSectionDetail>>();
以下是代码
public Map<Integer, List<CsSectionDetail>> getCsSectionDetail4Display(List<CsSectionDetail> list, boolean groupByMainTaskOnly) {
Map<Integer, List<CsSectionDetail>> map = new HashMap<Integer, List<CsSectionDetail>>();
Iterator<CsSectionDetail> it = list.iterator();
while(it.hasNext()){
CsSectionDetail csDetail = (CsSectionDetail) it.next();
add2Map(csDetail, map, groupByMainTaskOnly);
}
return map;
}
private void add2Map(CsSectionDetail csDetail, Map<Integer, List<CsSectionDetail>> map, boolean groupByMainTaskOnly) {
List<CsSectionDetail> list;
Integer key;
if (groupByMainTaskOnly) {
key = csDetail.getProjectTaskId().getId();
} else {
if (csDetail.getProjectSubTaskId() == 0) {
key = csDetail.getProjectTaskId().getId();
} else {
key = new Integer(csDetail.getProjectSubTaskId());
}
}
list = (List<CsSectionDetail>) map.get(key);
if (list == null) {
list = new ArrayList<CsSectionDetail>();
}
如何修改上面的代码来获取嵌套的地图结构?
由于
答案 0 :(得分:0)
为了清晰起见,用两种方法剪切代码,每种方法都在不同的级别填充地图:
private void add2TaskMap(CsSectionDetail csDetail, Map<Integer, Map<Integer,CsSectionDetail>> map) {
Map<Integer,CsSectionDetail> submap;
Integer key = csDetail.getProjectTaskId().getId();
submap =map.get(key);
if (submap == null) {
submap = new HashMap<Integer,CsSectionDetail>();
map.put(key, submap);
}
add2SubTaskMap(csDetail, submap);
}
private void add2SubTaskMap(CsSectionDetail csDetail, Map<Integer,CsSectionDetail> map) {
Integer key;
if (csDetail.getProjectSubTaskId() == 0) {
key = csDetail.getProjectTaskId().getId();
} else {
key = new Integer(csDetail.getProjectSubTaskId());
}
map.put(key, csDetail);
}