这是我的代码:
FileWriter writers = null;
try {
BufferedReader reader = new BufferedReader(new FileReader("Database.txt"));
ArrayList<Data> dataList = new ArrayList<>();
String line = "";
while ((line = reader.readLine()) != null) {
//split string and construct Data object and add it to dataList
dataList.add(parse(line));
}
reader.close();
Collections.sort(dataList);
writers = new FileWriter("final.txt");
for (Data d : dataList) {
writers.write(d.toString());
writers.write("rn");
}
writers.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
}
代码中的输入/输出:
input: mamy, 30, new, old
daddy, 21, new, new
output: daddy, 21,new,new
mamy , 30, new, old
预期输出:
daddy,21,new
mamy,30,new,old
我的问题是如何在存储到final.txt
之前删除重复数组?任何建议吗?
我认为Set非常适合你,它消除了重复。
Set<Data> dataSet = new HashSet<>(dataList);
要删除duplicates
,请在sorting
之前使用此代码。
ArrayList<Data> newDataList = new ArrayList<>();
for (Data element : dataList) {
if (!newDataList.contains(element)) {
newDataList.add(element);
}
}
dataList = newDataList;