从文本文件中删除重复行

3
我有一个文本文件,按字母顺序排序,大约有94,000行姓名(每行一个姓名,只有文本,没有标点符号)。
例如:
Alice Bob
Simon
Simon
Tom
每行的格式都相同,首字母大写,没有重音字母。
我的代码:
try{
        BufferedReader br = new BufferedReader(new FileReader("orderedNames.txt"));
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("sortedNoDuplicateNames.txt", true)));

        ArrayList<String> textToTransfer = new ArrayList();


        String previousLine = "";
        String current = "";

        //Load first line into previous line
        previousLine = br.readLine();

        //Add first line to the transfer list
        textToTransfer.add(previousLine);


        while((current = br.readLine()) != previousLine && current != null){

            textToTransfer.add(current);
            previousLine = current;
        }
        int index = 0;
        for(int i=0; i<textToTransfer.size(); i++){
            out.println(textToTransfer.get(i));
            System.out.println(textToTransfer.get(i));
            index ++;

        }
        System.out.println(index);

}catch(Exception e){
    e.printStackTrace();
}

据我理解,文件的第一行被读取并加载到previousLine变量中,就像我想的那样,current被设置为我们正在读取的文件的第二行,然后将current与上一行和null进行比较,如果它与上一行不同且不为null,则将其添加到数组列表中。
然后,previousLine被设置为当前值,以便下一个current的readLine可以替换当前的'current'值,继续在while循环中进行比较。
我看不出有什么问题。 如果发现重复,循环肯定应该停止吧?
提前道歉,如果结果证明是某些愚蠢的错误。

1
!(current = br.readLine()).equals(previousLine) - Pavneet_Singh
1
“List” 不像是这个问题的正确数据结构。我认为你想使用一些实现了“Set”的数据结构,因为它们不会像“List”那样存储重复项。在任意决定使用“ArrayList”之前,思考一下你选择数据结构的原因总是有好处的。查看此 SO 问题以获取详细信息 - Tom O.
3个回答

4

使用 TreeSet 替代 ArrayList。

Set<String> textToTransfer = new TreeSet<>();

TreeSet是有序的,不允许重复。


2

不要重复造轮子!

如果你不想有重复的元素,你应该考虑使用一个不允许重复元素的 Collection。最简单的方法是将内容添加到一个不允许重复元素的 Set 中:

import java.util.*;
import java.util.stream.*;

public class RemoveDups {
    public static void main(String[] args) {
        Set<String> dist = Arrays.asList(args).stream().collect(Collectors.toSet()); 
    }
}

另一种方法是在Java代码读取文件之前从文本文件中删除重复内容,例如在Linux中执行此操作(比在Java代码中执行更快):
sort myFileWithDuplicates.txt | uniq -u > myFileWithoutDuplicates.txt

1
虽然像其他人一样,我建议使用不允许重复条目进入集合的集合对象,但我认为我可以为您确定您的函数有什么问题。在您的While循环中尝试比较字符串(这当然是您要做的),您正在使用的方法在Java中是不正确的。 == (及其对应物)用于确定两个对象是否相同,这与确定它们的值是否相同不同。幸运的是,Java的String类具有静态字符串比较方法equals()。您可能需要像这样的东西:

while(!(current = br.readLine()).equals(previousLine) && current != null){

请记住,在此处中断您的While循环将强制停止文件读取,这可能是您想要的,也可能不是。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接