Jump to content
  • 0

Java, Map Descending Order


yess_boss

Question

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());
Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

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
Link to comment
Share on other sites

  • 0


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

}

}

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...