1

I am trying to sort a HashMap first by value (integer) then by key (string). The following method doesn't appear to be sorting the hashmap properly. Any ideas how to make it work properly ?

private static Map<String, Integer> sortHash(Map<String, Integer> map) {
 List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
 // Sort list by integer values then by string keys
 Collections.sort(list, (a, b) -> {
 int cmp1 = a.getValue().compareTo(b.getValue());
 if (cmp1 != 0)
 return cmp1;
 else
 return a.getKey().compareTo(b.getKey());
 });
 Map<String, Integer> result = new HashMap<>();
 for (Map.Entry<String, Integer> entry : list)
 result.put(entry.getKey(), entry.getValue());
 return result;
}
asked Nov 26, 2015 at 19:30
3
  • A better implementation of your comparator would be list.sort(Map.Entry.comparingByValue().thenComparing(Map.Entry.comparingByKey())) Commented Nov 26, 2015 at 19:43
  • @LouisWasserman Would i have to call this after i initialize my list ? This is what I am seeing. Not sure what exactly I am missing. Commented Nov 26, 2015 at 19:48
  • Will you not have a problem where you are just putting your results into a HashMap which has no guaranteed order? I think you'll need to look at TreeMap and supply a comparator to that. See link Commented Nov 26, 2015 at 20:42

1 Answer 1

3

The issue is here:

Map<String, Integer> result = new HashMap<>();

Use LinkedHashMap since this map will maintain the order of the addition of the key/value pairs.

answered Nov 26, 2015 at 19:32
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.