JAVA: Preventing Duplicate Entries to an ArrayList

前端 未结 6 1653

I am trying to prevent duplicate entries from being added to an ArrayList as the list is being populated whilst reading through each line of a file. Each line of the file is

6条回答
  •  别那么骄傲
    2021-01-12 00:57

    If you want to keep the order of the lines read keep using the list but for the duplicates you can use a set for determining if a line (in its two forms as you described) was already added :

    Set duplicates = new HashSet();
    while((line = bufferedReader.readLine()) != null) {
    
         String delimiter = "\t";
         String[] tempnodelist;  
         tempnodelist = line.split(delimiter);
    
         String lineReversed = tempnodelist[1] + delimiter + tempnodelist[0];
    
         if (!duplicates.contains(line) && !duplicates.contains(lineReversed )) {
             edges.add(line);
         }
    }
    

提交回复
热议问题