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<String> Common(List<List<String>> email1){        List<String> res= new ArrayList<String>();        HashMap<String,Integer> map = new HashMap<String,Integer>();        Set<String> set ;        int cou = 0;        for( List list : email1)        {            set = new HashSet<String>();            List<String> 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     }
Return list of common email ids from a list of lists
java;algorithm
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<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 setSystem.out.println(set);