Home >Java >javaTutorial >How to Remove Duplicate Emails from an Array in Java?
Eliminating Duplicate Emails in an Array
You want to remove duplicate emails from an array while reading them from a file. Here's a modified version of your code using a Set to achieve this:
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); } } } }
In this code:
The above is the detailed content of How to Remove Duplicate Emails from an Array in Java?. For more information, please follow other related articles on the PHP Chinese website!