Java Remove Duplicates from an Array?(Java从数组中删除重复项?)
问题描述
我应该读入一个包含许多不同电子邮件地址的文件并使用数组将它们打印出来.问题是我需要消除重复的电子邮件.
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.
我能够让我的 try/catch 工作并打印出电子邮件地址.但是,我不确定如何删除重复项.我还不了解哈希码或如何使用 Set
.任何帮助将不胜感激.
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.
这是我目前所拥有的:
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++;
}
}
}
}
推荐答案
简单的解决方案是使用java的Set,
The Simple solution is that use Set of java,
所以设置自动删除重复值
so set remove duplicate value automatically
在您的代码中,您有数组而不是转换数组以直接使用代码设置
and in your code you have array than convert array to set directly using code
Set<T> mySet = new HashSet<T>(Arrays.asList(someArray));
这篇关于Java从数组中删除重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java从数组中删除重复项?
基础教程推荐
- 如何对 HashSet 进行排序? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01