gpt4 book ai didi

java - 需要从文本文件中找到删除重复项,比较每行的第一个和第五个字符串

转载 作者:行者123 更新时间:2023-12-02 04:14:29 26 4
gpt4 key购买 nike

作为我正在进行的项目的一部分,我想清理我生成的文件中的重复行条目。然而,这些重复项通常不会出现在彼此附近。我想出了一种在 Java 中这样做的方法(基本上在文件中找到重复项,我将两个字符串存储在两个 arrayList 中并进行迭代,但它不起作用,因为嵌套的 for 循环我在很多方面都陷入了这种情况。

但是,我需要一个集成的解决方案。最好用Java。有任何想法吗?列表项

    public class duplicates {
static BufferedReader reader = null;
static BufferedWriter writer = null;
static String currentLine;

public static void main(String[] args) throws IOException {
int count=0,linecount=0;;
String fe = null,fie = null,pe=null;
File file = new File("E:\\Book.txt");

ArrayList<String> list1=new ArrayList<String>();
ArrayList<String> list2=new ArrayList<String>();

reader = new BufferedReader(new FileReader(file));

while((currentLine = reader.readLine()) != null)
{
StringTokenizer st = new StringTokenizer(currentLine,"/"); //splits data into strings
while (st.hasMoreElements()) {
count++;
fe=(String) st.nextElement();
//System.out.print(fe+"/// ");

//System.out.println("count="+count);
if(count==1){ //stores 1st string
pe=fe;
// System.out.println("first element "+fe);
}
else if(count==5){
fie=fe; //stores 5th string
// System.out.println("fifth element "+fie);
}
}
count=0;

if(linecount>0){
for(String s1:list1)
{
for(String s2:list2){
if(pe.equals(s1)&&fie.equals(s2)){ //checking condition
System.out.println("duplicate found");
//System.out.println(s1+ " "+s2);
}
}
}
}
list1.add(pe);
list2.add(fie);
linecount++;
}
}
}

i/p:

/book1/_cwc/B737/customer/Special_Reports/
/Airbook/_cwc/A330-200/customer/02_Watchlists/
/book1/_cwc/B737/customer/Special_Reports/
/jangeer/_cwc/Crj_200/customer/plots/
/Airbook/_cwc/A330-200/customer/02_Watchlists/
/jangeer/_cwc/Crj_200/customer/06_Performance_Summaries/
/jangeer/_cwc/Crj_200/customer/02_Watchlists/
/jangeer/_cwc/Crj_200/customer/01_Highlights/
/jangeer/_cwc/ERJ170/customer/01_Highlights/

o/p:

/book1/_cwc/B737/customer/Special_Reports/
/Airbook/_cwc/A330-200/customer/02_Watchlists/
/jangeer/_cwc/Crj_200/customer/plots/
/jangeer/_cwc/Crj_200/customer/06_Performance_Summaries/
/jangeer/_cwc/Crj_200/customer/02_Watchlists/
/jangeer/_cwc/Crj_200/customer/01_Highlights/

最佳答案

使用 Set<String>而不是Arraylist<String>

集合中不允许有重复项,因此如果您只是将每一行添加到其中,然后将它们取出,您将拥有所有不同的字符串。

就性能而言,它也比嵌套 for 循环更快。

关于java - 需要从文本文件中找到删除重复项,比较每行的第一个和第五个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33463697/

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