我有一个csv文件,我必须阅读csv文件并分别打印唯一,重复和无效的元素。 这是代码
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashSet;
public class InputData {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\e.csv"));
String line = null;
HashSet<String> lines = new HashSet<>();
HashSet<String> lines1 = new HashSet<>();
System.out.println("Unique List:- ");
while ((line = br.readLine()) != null)
{
{
try {
if (lines.add(line)) {
String[] part = line.split(",");
Integer.parseInt(part[0]);
System.out.println(line);
} else {
lines1.add(line);
}
} catch (NumberFormatException ne) {
System.out.println(" Invalid data:- " + ne);
}
}
}
br.close();
System.out.println("Duplicates:- " +lines1);
}
}
如果输入是
101,Ron,4545,XYZ,3
102,Harry,2345,ABC,3
103,Sam,5448,DEF,3
104,John,9989,GHI,3
101,Ron,4545,XYZ,3
104,John,9989,GHI,3
105,Gang,123,HNB,3
jftdgchj;vcvuigkuj;uygf
hvykfjtucd;gfd;gfd
我输出为: -
Unique List:-
101,Ron,4545,XYZ,3
102,Harry,2345,ABC,3
103,Sam,5448,DEF,3
104,John,9989,GHI,3
105,Gang,123,HNB,3
Invalid data:- java.lang.NumberFormatException: For input string: "jftdgchj;vcvuigkuj;uygf"
Invalid data:- java.lang.NumberFormatException: For input string: "hvykfjtucd;gfd;gfd"
Duplicates:- [101,Ron,4545,XYZ,3, 104,John,9989,GHI,3]
但我希望重复项分开......请帮忙
答案 0 :(得分:0)
你正在使用HashSet的默认.toString()方法,就像Stephen P在上面的评论中指出的那样。
改变这个:
System.out.println("Duplicates:- " +lines1);
这样的事情(使用enhanced for-loop迭代集合):
for (String s : lines1) {
System.out.println("Duplicates:- " + s);
}