如何将Subtitle结构的List <string []>转换为HashMap <string,list <string [] =“”>&gt; </string,> </string []>

时间:2013-12-11 04:56:24

标签: java loops hashmap

我有一个表格,显示一个字幕结构,按照从正确的顺序排列,从1,2,3 ...... TitleID是唯一的。

TitleID - Title - Level - Order
451 - History - Level1 - 1
123 - History of America - Level2 - 2
465 - History of Cali - Level3 - 3
578 - History of NewYork - Level3 - 4
765 - History of Europe - Level2 - 5
754 - History of West Europe - Level3 - 6

此表已转换为List<String[]> {"451", "History", "Level1", "1" }{"123", "History of America", "Level2", "2" } ...也是正确的顺序。

我想将此List<String[]>转换为HashMap<String, List<String[]>>。如果我手动执行它应该是这样的:

HashMap<String, List<String[]>> titleHashMap = new HashMap<String, List<String[]>>();

List<String[]> subTitleList=new ArrayList<String[]>;
String[] titles1={"123", "History of America", "Level2"};
subTitleList.add(titles1);
String[] titles12={"765", "History of Europe", "Level2"};
subTitleList.add(titles12);
titleHashMap.put("451", subTitleList);

List<String[]> subTitleList2=new ArrayList<String[]>;
String[] titles2={"465", "History of Cali" , "Level3"};
subTitleList2.add(titles2);

String[] titles21={"578", "History of NewYork", "Level3"};
subTitleList2.add(titles21);

titleHashMap.put("123", subTitleList2);

但我不想手动完成,所以如何自动完成? 注意:我还希望根级别为所有Level1的父级。例如,titleHashMap.put("root", subTitleListOfLevel1);

1 个答案:

答案 0 :(得分:1)

您的示例没有解释课程的分组方式以及地图的关键点。我假设课程按级别分组,关键是级别。但你可以轻松调整它。

// already exists:
List<String[]> lessons = ...

// final format
final HashMap<String, List<String[]>> titleHashMap = new HashMap<String, List<String[]>>();

for (String[] lesson : lessons) {
    final String level = lesson[2];
    if (!titleHashMap.containsKey(level)) {
        titleHashMap.put(level, new ArrayList<String[]>());
    }
    titleHashMap.get(level).add(lesson);
}