HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Return list of common email ids from a list of lists

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
emailreturnidslistslistfromcommon

Problem

Input: ArrayList of ArrayLists with email ids.

Output: Return ArrayList of email ids which appears in each inner ArrayList.

Ex: Input: [[abc@gmail.com, bca@gmail.com],[abc@gmail.com,bca@gmail.com,bca@gmail.com],[abc@gmail.com,xyz@gmail.com]]

Output: [abc@gmail.com]

I have written the code using HashSet and HashMap and could get the required output but I'm not sure how optimized and efficient my method is.

public static List Common(List> email1){

        List res= new ArrayList();
        HashMap map = new HashMap();
        Set set ;
        int cou = 0;
        for( List list : email1)
        {
            set = new HashSet();
            List temp = list;
            for(String i: temp){
                if(!set.contains(i)){
                    if(map.get(i) !=null){
                        map.put(i, map.get(i)+1);
                    }else{
                        map.put(i, 1);
                    }
                }
            }
            cou++;
        }

        int size = email1.size();

        for(String count: map.keySet()){
            if(map.get(count)== size)
            {
                System.out.println(count);
                res.add(count); 
            }
        }

        return res; // << this 
    }

Solution

Using a HashSet is fine, but you don't need to keep the count of occurrence of each email, you can just keep in the HashSet those that appear in all list, and remove all other emails.

//Need to check if email1 is empty before this step!
HashSet set = new HashSet(); 
set.addAll(email1.get(0));
for(int i = 1; i  tmp = new HashSet();
    for(String email : email1.get(i)){
        if(set.contains(email)){//If set contains this email, keep it!
           tmp.add(email);
        }
    }
    set = tmp;//Important step
}
//All emails will be in the set
System.out.println(set);

Code Snippets

//Need to check if email1 is empty before this step!
HashSet<String> set = new HashSet(); 
set.addAll(email1.get(0));
for(int i = 1; i < email1.size(); i++){
    HashSet<String> tmp = new HashSet();
    for(String email : email1.get(i)){
        if(set.contains(email)){//If set contains this email, keep it!
           tmp.add(email);
        }
    }
    set = tmp;//Important step
}
//All emails will be in the set
System.out.println(set);

Context

StackExchange Code Review Q#82342, answer score: 4

Revisions (0)

No revisions yet.