Home >Java >javaTutorial >How to Remove Duplicate Emails from an Array in Java?

How to Remove Duplicate Emails from an Array in Java?

Susan Sarandon
Susan SarandonOriginal
2024-11-13 05:36:02201browse

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:

  1. We create a Set named emailAddresses using HashSet. A Set is a collection that automatically removes duplicate values.
  2. We read the emails from the file as before.
  3. Instead of storing emails in an array, we add them to the emailAddresses Set using the add() method.
  4. This ensures that duplicate emails are removed from the Set.
  5. Finally, we iterate through the Set and print the unique email addresses.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn