Jump to content
  • 0

Java, Map Descending Order


Question

Posted

Hello guys, how can I sort out the values of  treemap in descending order? I think in default it is sorting the keys.

Map<L2PcInstance, Integer> newMap = new TreeMap<L2PcInstance, Integer>(Collections.reverseOrder());

2 answers to this question

Recommended Posts

  • 0
Posted (edited)

In your case, TreeMap is useless (until you use ordered keys somewhere else).

 

I would say you have to take the values() of HashMap (which is a Collection) into a new list, and then

Collections.sort(arraylist, Collections.reverseOrder());

More infos here :

 

http://www.leveluplunch.com/java/examples/sort-order-map-by-values/

 

If you want to keep ALSO keys, you have to build a Comparator. See "Straight up Java" case.

Edited by Tryskell
  • 0
Posted


public static Map<L2PcInstance, Integer> sortMap(Map<L2PcInstance, Integer> notSortedMap)

{

Map<L2PcInstance, Integer> orderedMap = new TreeMap<>(new MyOwnComparator(notSortedMap));

orderedMap.putAll(notSortedMap);

return orderedMap;

}

 

public static class MyOwnComparator implements Comparator<L2PcInstance>

{

private final Map<L2PcInstance, Integer> map;

 

public MyOwnComparator (Map<L2PcInstance, Integer> map)

{

this.map = map;

}

 

@Override

public int compare(L2PcInstance o1, L2PcInstance o2)

{

return Integer.compare(map.get(o1), map.get(o2));//Do whatever you want here. This line will currently compare the values

}

}

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


×
×
  • Create New...

Important Information

This community uses essential cookies to function properly. Non-essential cookies and third-party services are used only with your consent. Read our Privacy Policy and We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue..