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
Release: 2024-11-12 13:00:03
Original
406 people have browsed it

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));
Copy after login

Sort the List in ascending order:

Collections.sort(emailAddresses);
Copy after login

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
    }
}
Copy after login

Finally, convert the updated List back to an array:

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

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!

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