arraylist - How To Return number of duplicate string in the array list compare to another array list JAVA -
i need return how many time word duplicate if exist in arraylist
.
more explanation: if word in first arraylist
exist in arraylist wanna check how many times duplicate in second array list not working?
public int duplication(arraylist<string> studentlist, arraylist<string> teacherlist){ set<string> uniquestudent = new hashset<string>(studentlist); set<string> uniqueteacher = new hashset<string>(teacherlist); (string studentkey : uniquestudent) { (string teacherkey : uniqueteacher) { if(teacherkey.equals(studentkey)){ return collections.frequency(studentlist, studentkey); } } } }
the right datastructure store duplicates being considered map
, below code:
public static void main(string[] args) { map<string, integer> duplicatesmap = duplicate( new arraylist<string>(arrays.aslist(new string[] { "a", "h", "t", "p", "s", "o", "f", "x", "a" })), new arraylist<string>(arrays.aslist(new string[] { "a", "h", "t", "p", "s", "o", "f", "a", "o", "b", "x", "r" }))); (map.entry<string, integer> entry : duplicatesmap.entryset()) { system.out.println(entry.getkey() + " found " + entry.getvalue() + " times"); } } public static map<string, integer> duplicate(arraylist<string> fromlist, arraylist<string> tolist) { map<string, integer> returnmap = new hashmap<string, integer>(); set<string> uniquefromlist = new hashset<string>(fromlist); (string key : uniquefromlist) { if (tolist.contains(key)) { returnmap.put(key, collections.frequency(tolist, key)); } } return returnmap; }
output
t found 1 times f found 1 times found 2 times p found 1 times s found 1 times o found 2 times h found 1 times x found 1 times
Comments
Post a Comment