0

I have a TreeMap right now that holds 8 sets of , where it is sorted alphabetically based on the string. I basically need to display the top 5 sets based on their values (Integers). For example The treeMap might look like this:

{A = 5, B = 1, C = 10, D = 16, E = 7, F = 2, G = 11}

I would need it to print out:

D = 16, G = 11, C = 10, E = 7, A = 5

I don't think I can do this directly from a treeMap, but I was wondering if anyone knew. Thanks in advance!

HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47

2 Answers2

0

No, obviously it cannot be done by simply using a TreeMap as a TreeMap is ordered by key, not value.

You may consider maintaining a MultiMap (e.g. from Guava ) on the same time you maintain your original TreeMap (hence you have 2 Maps there. You may better encapsulate them into a new class though) , which you use the number as key, and the string as value. By using a MultiMap backed by a TreeMap, it should be trivial to find out first n entries with biggest number.

Adrian Shum
  • 38,812
  • 10
  • 83
  • 131
0

As Adrian Shum mentioned, there is no way to do it simply by using a TreeMap.

However, if you're okay with straying away from TreeMap, you can sort by value using a custom comparator, iterate over the results and print the first five entries. Note that the linked answer sorts ascending, so you will have to switch the order of comparison to sort descending.

Sort by value descending (taken and modified from the SO answer linked above):

import java.util.*

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map ) {

    List<Map.Entry<K, V>> list =
        new LinkedList<Map.Entry<K, V>>( map.entrySet() );
    Collections.sort( list, new Comparator<Map.Entry<K, V>>()
    {
        public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 )
        {
            return (o2.getValue()).compareTo( o1.getValue() );
        }
    } );

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list)
    {
        result.put( entry.getKey(), entry.getValue() );
    }
    return result;
}

Print the first five entries:

import java.util.*

Map<String, Integer> treeMap = // init to {A = 5,B = 1,...}
Map<String, Integer sortedByValue = sortByValue(treeMap);

int i = 0;
for (Map.Entry<String, Integer> entry : sortedByValue.entrySet()) {
    if (i < 5) {
        System.out.println(entry.getKey() + " = " + entry.getValue());
        i++;
    }
    else {
        // no need to keep looping once after we have printed the top 5 entries
        break;
    }
}
Community
  • 1
  • 1
Steven
  • 118
  • 8