从Java数组删除重复? [英] Java Remove Duplicates from an Array?

查看:96
本文介绍了从Java数组删除重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我能得到我的try / catch工作,并打印出来的电子邮件地址。但是,我不知道如何去删除重复项。我没有哈希code的的理解或如何使用设置呢。任何援助将AP preciated。

下面是我到目前为止有:

 进口java.util.Scanner中;
进口java.io. *;公共类重复{
   公共静态无效的主要(字串[] args){      扫描仪键盘=新的扫描仪(System.in);
      的System.out.println(输入文件名:);
      字符串文件名= keyboard.nextLine();
      如果(fileName.equals()){
         的System.out.println(错误:用户没有指定的文件名。);
      }其他{
         扫描仪的InputStream = NULL;         尝试{
            的InputStream =新扫描仪(新文件(文件名));
         }赶上(FileNotFoundException异常五){
            的System.out.println(错误:+文件名+。不存在);
            System.exit(0);
         }         的String []地址=新的String [100];         INT I = 0;
         而(inputStream.hasNextLine()){
            字符串email = inputStream.nextLine();
            //的System.out.println(电子邮件);            地址[I] =电子邮件;
            的System.out.println(地址[I]);
            我++;
         }
      }
   }
}


解决方案

简单的解决方法是Java的那使用SET,

所以设置自动删除重复值

和在你的code你有数组转换比直接arrayto通过设置code

 设置< T> MYSET =新的HashSet< T>(Arrays.asList(的someArray));

I am supposed to read in a file containing many different email addresses and print them out using an array. The problem is I need to eliminate duplicate emails.

I was able to get my try / catch working and print out the email addresses. However, I am not sure how to go about removing the duplicates. I do not have an understanding of hashcode's or how to use a Set yet. Any assistance would be appreciated.

Here is what I have so far:

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

解决方案

The Simple solution is that use SET of java,

so set remove duplicate value automatically

and in your code you have array than convert arrayto set directly using code

Set<T> mySet = new HashSet<T>(Arrays.asList(someArray));

这篇关于从Java数组删除重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆