user3287300
user3287300

Reputation: 151

Splitting Strings while putting them into a TreeMap

I am reading these in with a 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-,"

I want to try to break up these lines of strings, take the first word of each line and plug that into the key of a TreeMap, then plug the words following that into the mapped values of the TreeMap

So I was thinking of doing this...

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

However, I am not sure how to make a loop, so it does this for every String line.

My current output would produce:

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

But I want it to produce:

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

Upvotes: 0

Views: 421

Answers (1)

Mark Elliot
Mark Elliot

Reputation: 77054

You just need to loop over the lines, the pattern is something like:

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

Upvotes: 1

Related Questions