消除数组中的重复电子邮件
您希望在从文件读取重复电子邮件时从数组中删除重复的电子邮件。下面是使用 Set 来实现此目的的代码的修改版本:
import java.util.Scanner; import java.io.*; import java.util.Set; import java.util.HashSet; 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); } // Use a Set to automatically remove duplicate values Set<String> emailAddresses = new HashSet<>(); while (inputStream.hasNextLine()) { String email = inputStream.nextLine(); // Add email to the Set, which ignores duplicates emailAddresses.add(email); } // Print the unique email addresses for (String email : emailAddresses) { System.out.println(email); } } } }
在此代码中:
以上是如何从 Java 数组中删除重复的电子邮件?的详细内容。更多信息请关注PHP中文网其他相关文章!