Java从数组中删除重复项?

Bea*_*inz 7 java arrays duplicates

我应该在包含许多不同电子邮件地址的文件中读取并使用数组打印出来.问题是我需要消除重复的电子邮件.

我能够让我的try/catch工作并打印出电子邮件地址.但是,我不知道如何删除重复项.我不了解哈希码或如何使用哈希码Set.任何援助将不胜感激.

这是我到目前为止:

import java.util.Scanner;
import java.io.*;

public class Duplicate {
   public static void main(String[] args) {

      Scanner keyboard = new Scanner(System.in);
      System.out.println("Enter file name: ");
      String fileName = keyboard.nextLine();
      if (fileName.equals("")) {
         System.out.println("Error: User did not specify a file name.");
      } else {
         Scanner inputStream = null;

         try {
            inputStream = new Scanner(new File(fileName));
         } catch (FileNotFoundException e) {
            System.out.println("Error: " + fileName + " does not exist.");
            System.exit(0);
         }

         String[] address = new String[100];

         int i = 0;
         while (inputStream.hasNextLine()) {
            String email = inputStream.nextLine();
            // System.out.println(email);

            address[i] = email;
            System.out.println(address[i]);
            i++;
         }
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

Yog*_*ati 32

简单的解决方案是使用Set of java,

所以设置自动删除重复值

并且在你的代码中你有数组而不是直接使用代码转换数组

Set<T> mySet = new HashSet<T>(Arrays.asList(someArray));
Run Code Online (Sandbox Code Playgroud)


spa*_*ead 5

学习Set.学习它所花费的时间少于编写不使用它的时间.

我会帮你的 替换这个:

String[] address = new String[100];

有了这个:

Set<String> addresses = new HashSet<String>();

还有这个:

address[i] = email;

有了这个:

addresses.add(email);

你不再需要i了.

你完成了.如果您想要打印出来:

for (String address : addresses) {
     System.out.println (address);
}
Run Code Online (Sandbox Code Playgroud)

这几乎涵盖了它.希望一切都自动排序?替换HashSet上面的TreeSet.现在去阅读这个优秀的教程,以便下次,你可以更快地自己完成所有这些.


小智 3

您可以尝试遍历数组中的每个元素,将其添加到另一个元素,检查第二个数组是否包含下一项(如果确实跳过它)。然后只需将第一个数组替换为第二个数组即可。(ArrayList不过在这种情况下更好)。

所以像这样:

List<String> FinalList = new ArrayList<String>();
for(string temp : adress)
{
if(!FinalList.contains(temp))
  FinalList.add(temp);
}
Run Code Online (Sandbox Code Playgroud)