Java Interview Practice Problem (Beginner): Distinct Email IDs

  • Post last modified:September 10, 2023
  • Reading time:3 mins read

Problem

  • The Frontend application allows the marketing team to upload email addresses. But there maybe cases where this upload feature contains duplicate email addresses which will cause a unique constraint violation in the database.
  • Write a Java program that reads and outputs only unique user emails so that I can persist into the database without any constraint violation.

Example

input email list

  • Our input list contains an email address. As we can see there is a duplicate for “pqr@pqr.com”, and “abc@abc.com”.
[zt1jegib68@abc.com, 95fv6s8e1m@gmail.com, pijuupwmwa@gmail.com, pqr@pqr.com, pqr@pqr.com, abc@abc.com, abc@abc.com]

Output

  • Our output only has one occurrence of “pqr@pqr.com”, and “abc@abc.com”.
[zt1jegib68@abc.com, 95fv6s8e1m@gmail.com, pijuupwmwa@gmail.com, pqr@pqr.com, abc@abc.com]

Before jumping to the solution consider giving an attempt.

Solution

Sample Input Data

 public static void main(String[] args) {
      Common common = new Common();
      List<String> input = common.getEmailList();
      System.out.println(input);
}

Solution 1

  • In this solution, we are iterating over the input list and storing it in a hashmap. Hashmap doesn’t allow us to insert duplicate keys so for cases where we have 2 or more email IDs, it will essentially be a replace operation in hashmap and hashmap will have only one occurrence of that email
  • Once we have a hashmap, we can convert hashmap keys into a list and return it.
       public static List<String> solution1(List<String> input) {
        Map<String, Integer> emailMap = new HashMap<>();
        input.forEach(e ->emailMap.putIfAbsent(e, 1));
        return emailMap.keySet().stream().toList();
    }

Solution 2

  • This solution is similar to solution 1. Instead of a hashmap, it’s logical to use HashSet since we don’t need an occurrence count.
  • HashSet only stores distinct values. We can initialize HashSet with input and then convert it back to a list.
    public static List<String> solution2(List<String> input) {
        return new HashSet<>(input).stream().toList();
    }

Solution 3

Java streams API also provides a distinct method to select only distinct elements and store them in a collection.

    public static List<String> solution3(List<String> input) {
        return input.stream()
            .distinct()
            .toList();
    }

Code

Find all the code for this & other exercises on GitHub

Over to youWrite down your solution in the comment section for others to get back to it

Before You Leave

Other Problems List

Leave a Reply