Wednesday, 13 December 2017

Get the Number of Duplicate Elements in the List or Array

public class NoOfDuplicateElementsInTheList {

public static void main(String[] args) {
// TODO Auto-generated method stub
String[] arr = {"cat","dog","cow","cat","dog","mice"};
Map<String,Integer> mp= new HashMap<String,Integer>();
for(int i=0;i<arr.length;i++){
if(mp.containsKey(arr[i])){
mp.put(arr[i], mp.get(arr[i])+1) ;
}else{
mp.put(arr[i], 1);
}
}
for(Entry<String,Integer> e : mp.entrySet()){
System.out.println(e.getKey() +"-"+e.getValue());
}

}


}

No comments:

Post a Comment