Reputation: 1
I have been asked to create a toArray
method which should return an Iterator or array, respectively, with elements sorted by their “add” counts (values in the HashMap) in ascending order.
However, I am getting the following error message and don't know how to fix it:
The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (Set<Map.Entry<T,Integer>>, new Comparator<Map.Entry<T,Integer>>(){})
So it seems like I have to override or create the sort method. Can someone help point me in the right direction?
public class OccurenceSet<T> implements Set<T>{
private HashMap<T,Integer> data;
public OccurenceSet(){
this.data = new HashMap<T,Integer>();
}
@Override
public Object[] toArray() {
Set<Map.Entry<T,Integer>> dataSet = data.entrySet();
ArrayList<Map.Entry<T,Integer>> dataList = new ArrayList<>(dataSet);
Collections.sort(dataSet, new Comparator<Map.Entry<T,Integer>>() {
@Override
public int compare(Map.Entry<T,Integer> o1, Map.Entry<T, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
return null;
}
}
Upvotes: 0
Views: 693
Reputation: 7730
"The method sort(List, Comparator) in the type Collections is not applicable for the arguments (Set>, new Comparator>(){})"
You are getting this exception because Collections#sort
method can only accept List<T>
not a Set
More Information here : Collections#sort Method
Upvotes: 2
Reputation: 121
HashMap is not meant to keep entries in sorted order, but if you have to sort HashMap based upon keys or values, you can do that in Java.
Upvotes: 2