我有一个输入文件如下:
conf/iastedCSN/KangHPLNL06 Quoc V. Phung
conf/iastedCSN/KangHPLNL06 Kungmeng Lo
conf/iastedCSN/KangHPLNL06 Hoang Nam Nguyen
conf/iastedCSN/KangHPLNL06 M. M. Lee
series/sci/ZighedAB13 Djamel Abdelkader Zighed
series/sci/ZighedAB13 Rafik Abdesselam
series/sci/ZighedAB13 Ahmed Bounekkar
series/sci/LermanG13 Isra챘l-C챕sar Lerman
我想用分隔符输出如下:
conf/iastedCSN/KangHPLNL06 | QuocV.Phung
conf/iastedCSN/KangHPLNL06 | KungmengLo
conf/iastedCSN/KangHPLNL06 | HoangNamNguyen
conf/iastedCSN/KangHPLNL06 | M.M.Lee
series/sci/ZighedAB13 | DjamelAbdelkaderZighed
series/sci/ZighedAB13 | RafikAbdesselam
series/sci/ZighedAB13 | AhmedBounekkar
series/sci/LermanG13 | Isra챘l-C챕sarLerman
但是现在,我在结果中重复了很多行,我似乎无法找出原因。 我得到的输出如下:
conf/iastedCSN/KangHPLNL06 | QuocV.Phung
conf/iastedCSN/KangHPLNL06 | KungmengLo
conf/iastedCSN/KangHPLNL06 | HoangNamNguyen
conf/iastedCSN/KangHPLNL06 | M.M.Lee
conf/iastedCSN/KangHPLNL06 | M.M.Lee
series/sci/ZighedAB13 | DjamelAbdelkaderZighed
conf/iastedCSN/KangHPLNL06 | M.M.Lee
series/sci/ZighedAB13 | RafikAbdesselam
conf/iastedCSN/KangHPLNL06 | M.M.Lee
series/sci/ZighedAB13 | AhmedBounekkar
conf/iastedCSN/KangHPLNL06 | M.M.Lee
series/sci/LermanG13 | Isra챘l-C챕sarLerman
series/sci/ZighedAB13 | AhmedBounekkar
以下是源代码:
package authorgraph;
import java.io.*;
import java.util.*;
public class graph {
private static BufferedReader br;
public static void main(String[] args)
{
try{
br = new BufferedReader (new FileReader ("inproceedings-author-test1.txt"));
Map<String, String> items = new TreeMap<String, String>();
String line;
while (null != (line = br.readLine()))
{
String[] line_parts = line.split(" ");
if (line_parts.length > 1)
{
StringBuilder name = new StringBuilder(line_parts[1]);
for (int i = 2; i < line_parts.length; i++)
{
name.append(line_parts[i]);
}
items.put(new String(line_parts[0]), name.toString());
}
for (String conf: items.keySet())
{
System.out.println(conf + " | " + items.get(conf));
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
};
任何帮助都会非常感激
答案 0 :(得分:2)
new String
中的items.put(new String(line_parts[0]), name.toString());
无用。字符串是不可变的,如果你已经有一个String,就不需要创建一个新字符串。
你得到重复,因为for
没有放在正确的位置:你每次读一行都要执行它。
for (String conf: items.keySet())
{
System.out.println(conf + " | " + items.get(conf));
}
} // end of while
请改为:将for
移到while
循环之外。
} // end of while
for (String conf: items.keySet())
{
System.out.println(conf + " | " + items.get(conf));
}
而不是在keySet()
上执行循环,请执行以下操作:
for (Map.Entry<String, String> entry : items.entrySet()) {
System.out.println(entry.getKey() + " | " + entry.getValue());
}
Map<K,V>.entrySet()
将返回Map.Entry<K,V>
。条目是密钥及其值之间的关联。