如何在数组中查找重复项 - Java

时间:2017-02-23 14:55:34

标签: java

我目前拥有在Java中完全正常运行的代码。它需要一个字符串,将其转换为数组并删除所有重复项。我决定用字符串"一名水手去海海看看他能看到的东西看到的东西,但他能看到的所有东西看到的是深蓝色的大海海底#34;我使用它,因为它有大量的重复。

要添加到代码中我希望能够获得数组中所有元素的位置,我相信正确的方法是通过嵌套循环,但我不知道如何实现这一点。如果有人有一些指导甚至一般的想法,我会很满意。

以下是当前代码:

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);
}
}

}

1 个答案:

答案 0 :(得分:0)

您的代码很好,但如果订单很关键,为什么不使用LinkedHashSet? 将元素添加到linkedhashset,然后按照添加的顺序将它们恢复,只需将条目作为toString()。您将使用逗号分隔返回的单词,但可以轻松删除它们。它看起来像&#34; [a,水手,去,去,海,看,有什么...]&#34;

 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(",");
   }