Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

Email addresses make application software more efficient in user identification and communication. In the case of a list of email addresses, the distinction between unique addresses and the removal of duplicates becomes necessary.

In this tutorial, we’ll analyze multiple methods that can be applied to find unique email addresses in a list using Java.

2. String Manipulation Approach

For the list of email addresses, the goal is to pick up the unique email addresses, ignoring case sensitivity. For example, “[email protected]” and “[email protected]” are the same email addresses.

In this approach, we can use a HashSet to store unique emails efficiently, as the nature of a Hashset ensures that duplicate emails are automatically discarded. Let’s take an example:

@Test
public void givenEmailList_whenUsingStringManipulation_thenFindUniqueEmails() {
    Set<String> uniqueEmails = new HashSet<>();
    for (String email : emailList) {
        uniqueEmails.add(email.toLowerCase());
    }

    assertEquals(expectedUniqueEmails, uniqueEmails);
}

Here, we start by initializing a HashSet named uniqueEmails to store unique email addresses. Afterward, the loop iterates through each email in the provided list, converting it to lowercase using the toLowerCase() method to make the comparison case-insensitive. Then, we add this pre-processed email to the uniqueEmails HashSet.

Finally, we employ the assertEquals() method to verify that the emails in expectedUniqueEmails match the email uniqueEmails set obtained through the string manipulation process.

3. Java Streams Approach

Java Streams provides an easy solution for processing collections by utilizing the filtering option and collecting unique email addresses. Let’s delve into a simple example:

@Test
public void givenEmailList_whenUsingJavaStreams_thenFindUniqueEmails() {
    Set<String> uniqueEmails = Arrays.stream(emailList)
      .map(String::toLowerCase)
      .collect(Collectors.toSet());

    assertEquals(expectedUniqueEmails, uniqueEmails);
}

In this test method, we first convert each email to lowercase using the toLowerCase() method. Also, we utilize the toSet() method to collect elements into a HashSet.

4. Conclusion

In conclusion, we have presented various techniques for isolating exclusive email addresses from the list in Java. Whether through basic string manipulation or by utilizing Java Streams, the target is to discover and eliminate duplicates using the domain and username.

As always, the complete code samples for this article can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.