gpt4 book ai didi

java - 使用 Java 从文本中删除重复行

转载 作者:搜寻专家 更新时间:2023-11-01 01:29:31 25 4
gpt4 key购买 nike

我想知道是否有人在 java 中具有删除重复行同时保持行顺序的逻辑。

我不喜欢正则表达式解决方案。

最佳答案

public class UniqueLineReader extends BufferedReader {
Set<String> lines = new HashSet<String>();

public UniqueLineReader(Reader arg0) {
super(arg0);
}

@Override
public String readLine() throws IOException {
String uniqueLine;
if (lines.add(uniqueLine = super.readLine()))
return uniqueLine;
return "";
}

//for testing..

public static void main(String args[]) {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(
"test.txt");
UniqueLineReader br = new UniqueLineReader(new InputStreamReader(fstream));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
if (strLine != "")
System.out.println(strLine);
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}

}

修改版本:

public class UniqueLineReader extends BufferedReader {
Set<String> lines = new HashSet<String>();

public UniqueLineReader(Reader arg0) {
super(arg0);
}

@Override
public String readLine() throws IOException {
String uniqueLine;
while (lines.add(uniqueLine = super.readLine()) == false); //read until encountering a unique line
return uniqueLine;
}

public static void main(String args[]) {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(
"/home/emil/Desktop/ff.txt");
UniqueLineReader br = new UniqueLineReader(new InputStreamReader(fstream));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}

}
}

关于java - 使用 Java 从文本中删除重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5931665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com