消除陣列中的重複電子郵件
您希望在從檔案讀取重複電子郵件時從陣列中刪除重複的電子郵件。以下是使用 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中文網其他相關文章!