将字符串拆分为TreeMap时拆分字符串

时间:2014-04-13 23:30:46

标签: java arrays

我正在使用BufferedReader ...

阅读这些内容
"A+,G.W.Bush,B.H.Obama,J.F.Kennedy"
"A-,A.Lincoln,U.S.Grant,L.B.Johnson,G.A.Ford,W.J.Clinton"
"B+,T.L.Hoffman,F.D.Roosevelt,J.A.Garfield"
"O,R.M.Nixon,G.Cleveland,C.A.Arthur"
"B-,"

我想尝试分解这些字符串,取每行的第一个字并将其插入TreeMap的键中,然后将其后的字插入TreeMap的映射值

所以我想这样做......

    BufferedReader infile = new BufferedReader(new FileReader(args[0]));

    ArrayList<String> typetopres = new ArrayList<String>(
            Arrays.asList(infile.readLine().split(",")));

    TreeMap<String, ArrayList<String>> tm = new TreeMap<String, ArrayList<String>>();

    String type= typetopres.remove(0);

    tm.put(type, typetopres);

    System.out.println(tm);

但是,我不知道如何进行循环,因此它为每个String行执行此操作。

我当前的输出会产生:

{A+=[G.W.Bush, B.H.Obama, J.F.Kennedy]}

但我想要它产生:

A+ = [G.W.Bush, B.H.Obama, J.F.Kennedy] 
A- = [A.Lincoln, U.S.Grant, L.B.Johnson, G.A.Ford, W.J.Clinton]
B+ = [T.L.Hoffman, F.D.Roosevelt, J.A.Garfield]
and so on...

1 个答案:

答案 0 :(得分:1)

你只需要遍历这些线条,模式就像:

BufferedReader infile = new BufferedReader(new FileReader(args[0]));
TreeMap<String, ArrayList<String>> tm = new TreeMap<String, ArrayList<String>>();

String line;
while ((line = infile.readLine()) != null) {
    ArrayList<String> typetopres = new ArrayList<String>(
        Arrays.asList(line.split(",")));

    String type= typetopres.remove(0);

    tm.put(type, typetopres);
}

System.out.println(tm);

infile.close(); // don't forget to cleanup