具有相同密钥树集的多个值

时间:2013-12-07 00:58:26

标签: java treeset

我有一个包含这样的数据的文本文件

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

我使用缓冲的阅读器将文本加载到Treeset的字符串中,然后打印该集。 接下来我想分隔名称后跟名称,即

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

如何分别为每个名称指定密钥?我尝试使用split来用逗号分隔字符串,但我无法让它工作。我试过了:

TreeSet<String> set1 = loadSetFromFile( infile2 ); 

然后创建一个新列表并使用split将逗号与此行分开

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

显然不是正确的事情。我在想,也许我必须在我的set loading方法中做到这一点

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

然后,我必须以某种方式将该行的第一个字母与以下所有内容相关联。不知道怎么做。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我认为你过于复杂了。

假设您的my/path中有一个名为foo.txt的文件,其中包含示例中的文字,这里有一种处理数据的方法,只需MapString.split, Java 6风格:

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

<强>输出

{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+