簡體   English   中英

如何在數組中查找重復項-Java

[英]How to find duplicates within an array - Java

目前,我擁有可以在Java中完全正常運行的代碼。 它需要一個字符串,將其轉換為數組並刪除所有重復項。 我決定使用字符串“一個水手去了大海看他能看見的東西,但是他所能看見的只是深藍色的大海的底部”。 我使用了它,因為它有大量重復項。

為了添加到代碼中,我希望能夠獲取數組中所有元素的位置,我相信正確的方法是通過嵌套循環,但是我不確定如何實現此目的。 如果有人有指導或什至一般性的想法,我會很高興。

這是當前代碼:

static ArrayList<String> removeDuplicates(String[] list) {
// Store unique items in result.
ArrayList<String> result = new ArrayList<>();
// Record encountered Strings in HashSet.
HashSet<String> set = new HashSet<>();
// Loop over argument list.
for (String item : list) {
    // If String is not in set, add it to the list and the set.
    if (!set.contains(item)) {
    result.add(item);
    set.add(item);
    }
}
return result;
}
public static void main(String[] args) {
    String sea1 = "A sailor went to sea sea sea, to see what he could see see see, but all that he could see see see, was the bottom of the deep blue sea sea sea";
    String sea2 = sea1.toLowerCase(); 
    String sea3 = sea2.replaceAll("[\.:;,\"!\?]", " "); //remove punctuation + sets to lower case
    String sea4 = sea3.replaceAll("  ", " ");
    String sea5 = sea4.replaceAll(" ", ",");
    String sea6 = sea5.replaceAll("'", " ");
    String sea7 = sea6.replaceAll(" ", "");
    System.out.println("Here is the string: " + sea7);

String[] sealist = sea7.split(",");
    System.out.println("Here is the string 'end' with duplicates removed: ");

// Remove duplicates from ArrayList of Strings.
ArrayList<String> unique = removeDuplicates(sealist);
for (String element : unique) {

    System.out.println("- " + element);
}
}

}

您的代碼不錯,但是如果順序很關鍵,為什么不使用LinkedHashSet? 將元素添加到linkedhashset,然后按照添加順序將它們取回,只需將條目作為toString()即可獲取。 您將使用逗號分隔返回的單詞,但是可以輕松刪除它們。 它看起來像“ [水手,去,到海,看,什么...]”

 static ArrayList<String> removeDuplicates(String[] list) {
      // Record encountered Strings in HashSet.
      LinkedHashSet<String> set = new LinkedHashSet<>();
      // Loop over argument list.
      for (String item : list) {
          // Left this if statement in for clarity (!needed)
          if (!set.contains(item)) {
              set.add(item);
           }
      }

      String result= set.toString(); 
      return(result.split(",");
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM