0

I am attempting to sort a hashMap by value, I have a method

public void sortByValues(HashMap inMap, HashMap<Character, Float> outMap) {
        List list = new LinkedList(inMap.entrySet());
        // Defined Custom Comparator here
        Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) ((Map.Entry) (o2)).getValue()).compareTo(((Map.Entry) (o1)).getValue());
            }
        });

    // Here I am copying the sorted list in HashMap
    // using LinkedHashMap to preserve the insertion order
    for (Iterator it = list.iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();
        outMap.put(entry.getKey(), entry.getValue());
    }
}

The keys are chars, and the values are floats. However I cannot enter the sorted keys/values into the outMap because entry.getKey() is of type Object. How can I change this so that it puts a Key(char) and Value(float) into the outMap rather than both being objects?

H_Lev1
  • 253
  • 4
  • 18
  • Also, don't use `LinkedList` for this. Sorting a `LinkedList` is very inefficient compared to sorting an `ArrayList`. – Andy Turner Dec 01 '17 at 15:00
  • The faint irony here is that if you'd omitted the `` from `outMap`'s type declaration, thereby using raw types everywhere, you may not have known there was a problem here. – Andy Turner Dec 01 '17 at 15:12

1 Answers1

0

try something like that

public <K extends Comparable, V extends Comparable> void sortByValues(final Map<K, V> inMap, 
                                                                        HashMap<Character, Float> outMap) {

    inMap.entrySet()
        .stream()
        .sorted((it1, it2) -> it1.getValue().compareTo(it2.getValue()))
        .forEachOrdered(it -> outMap.put((Character) it.getKey(), (Float) it.getValue()));

  }
dzrkot
  • 543
  • 2
  • 4
  • 23