Home > Java > javaTutorial > How to Eliminate Duplicate Email Addresses in Java Using a HashSet?

How to Eliminate Duplicate Email Addresses in Java Using a HashSet?

Susan Sarandon
Release: 2024-11-13 10:57:02
Original
1060 people have browsed it

How to Eliminate Duplicate Email Addresses in Java Using a HashSet?

Unique Email Address Detection in Java

Your goal is to remove duplicate emails from an array of addresses stored in a file. Here's how you can achieve this using a Set data structure:

In the provided code, an array, address, is used to store emails. However, to eliminate duplicates, you can leverage the HashSet class.

HashSet in Java

A HashSet is a collection of unique elements. When you add an element to a HashSet that already exists, it is not added again. This property makes it ideal for removing duplicates.

Code Modification

To use a HashSet to remove duplicates from your array, modify the code as follows:

  1. Create a new HashSet called uniqueEmails.
  2. Iterate through the address array and add each email to the uniqueEmails HashSet.
  3. Convert the uniqueEmails HashSet back into an array using the toArray() method and store it in uniqueAddress.
// Create a HashSet for storing unique emails
Set<String> uniqueEmails = new HashSet<>();

// Iterate through the address array and add each email to the HashSet
for (String email : address) {
    uniqueEmails.add(email);
}

// Convert the HashSet back into an array
String[] uniqueAddress = uniqueEmails.toArray(new String[uniqueEmails.size()]);

// Print the unique email addresses
for (String email : uniqueAddress) {
    System.out.println(email);
}
Copy after login

This modified code ensures that all duplicate emails are eliminated and that only unique addresses remain in the uniqueAddress array.

The above is the detailed content of How to Eliminate Duplicate Email Addresses in Java Using a HashSet?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template