Home >Java >javaTutorial >How Can I Remove Duplicate Emails from an Array in Java Without Using Hashcodes or Sets?

How Can I Remove Duplicate Emails from an Array in Java Without Using Hashcodes or Sets?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-12 13:00:03419browse

How Can I Remove Duplicate Emails from an Array in Java Without Using Hashcodes or Sets?

Removing Duplicate Emails in an Array in Java

In your Java program, you need to eliminate duplicate email addresses from an array. Here's how you can achieve this without using hashcodes or Sets:

Convert the array to a List:

List<String> emailAddresses = new ArrayList<>(Arrays.asList(address));

Sort the List in ascending order:

Collections.sort(emailAddresses);

Now, you can iterate through the sorted List and check for consecutive duplicate emails:

for (int i = 0; i < emailAddresses.size() - 1; i++) {
    if (emailAddresses.get(i).equals(emailAddresses.get(i + 1))) {
        // If current and next emails are same, remove the next one
        emailAddresses.remove(i + 1);
        i--; // Decrement i to avoid skipping an email
    }
}

Finally, convert the updated List back to an array:

address = emailAddresses.toArray(new String[0]);

This modified code will effectively remove duplicate email addresses from the array while preserving their order.

The above is the detailed content of How Can I Remove Duplicate Emails from an Array in Java Without Using Hashcodes or Sets?. 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