Novice
Novice

Reputation: 1

Collections.sort() on Generic Data Structure not working

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

Answers (2)

Neeraj Jain
Neeraj Jain

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

Namrata Choudhary
Namrata Choudhary

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.

  1. Get all entries by calling entrySet() method of Map
  2. Create a custom Comparator to sort entries based upon values.
  3. Convert entry set to list.
  4. Sort entry list by using Collections.sort() method by passing your value comparator
  5. Create a LinkedHashMap by adding entries in sorted order.

Upvotes: 2

Related Questions