multiple values with same key tree set

2.1k Views Asked by At

I have a text file with some data like this

A+,John,James,Henry
B+,Andrew,Chris,Andy
O,Grant,Celina,Claudia

I use buffered reader to load the text into a Treeset of string, and print the set. Next I want to separate the names followed by the key i.e.

John A+
James A+
Henry A+
Andrew B+ 
etc.

How can I assign the key to each of the names separately? I tried using split to separate the strings by commas, but I couldn't get it to work. I tried doing:

TreeSet<String> set1 = loadSetFromFile( infile2 ); 

and then making a new list and using split to separate the commas with this line

List<String> splitlist = Arrays.asList(set1.split(","));//dont work

Obviously not the correct thing to do. I was thinking that maybe I would have to do it in my set loading method

  static TreeSet<String> loadSet( BufferedReader infile ) throws Exception
     {TreeSet<String> set = new TreeSet<String>();
      while( infile.ready() )
        set.add(infile.readLine());//split(",") lol
      infile.close();
      return set;
     }

I would then have to somehow associate the first letter of the line with all of the following. Don't know how to do that either. Any help would be greatly appreciated.

1

There are 1 best solutions below

3
On

I think you're over-complicating this.

Presuming you have a file in my/path named foo.txt containing the text in your example, here's a way to process your data, with a simple Map and String.split, Java 6 style:

BufferedReader br = null;
try {
     br = new BufferedReader(new InputStreamReader(new FileInputStream(
            new File("/my/path/foo.txt"))));
     String line = null;
     Map<String, String> input = new HashMap<String, String>();
     while ((line = br.readLine()) != null) {
         // splitting each line of the file by commas
         String[] splitted = line.split(",");
         // iterating over splitted Strings
         for (int i = 1; i < splitted.length; i++) {
             // putting each value into map as key (starting at 2nd value), 
             // with value as first element of the splitted String
             input.put(splitted[i], splitted[0]);
         }
     }
     // printing the map
     System.out.println(input);
     // printing the map "nicely"
     for (String key: input.keySet()) {
         System.out.println(key.concat(" ").concat(input.get(key)));
     }
}
// your typical exception "handling"
catch (FileNotFoundException fnfe) {
    fnfe.printStackTrace();
}
catch (IOException ioe) {
    ioe.printStackTrace();
}
// Java 6 style resource closing
finally {
    if (br != null) {
        try {
            br.close();
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

Output

{Henry=A+, Celina=O, Grant=O, James=A+, Claudia=O, Andrew=B+, John=A+, Andy=B+, Chris=B+}

Henry A+
Celina O
Grant O
James A+
Claudia O
Andrew B+
John A+
Andy B+
Chris B+