Created
November 16, 2019 17:23
-
-
Save Tancred423/f62796d113ffcbc659ecc2eb61b510fe to your computer and use it in GitHub Desktop.
Sorting HashMap by Value then Key
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Main { | |
public static void main(String[] args) { | |
// Your unsorted map - an example | |
final Map<String, Integer> unsortedMap = new HashMap<>(); | |
unsortedMap.put("User B", 50); | |
unsortedMap.put("User C", 100); | |
unsortedMap.put("User A", 50); | |
// Printing in console to show the current unsorted map | |
System.out.println("Unsorted Hash Map:"); | |
for (var entry : unsortedMap.entrySet()) System.out.println(entry.getKey() + ": " + entry.getValue()); | |
// Call method to sort it | |
var sortedLinkedHashMap = sortHashMap(unsortedMap); | |
// Printing in console to show the sorted map | |
System.out.println("\nSorted Linked Hash Map:"); | |
for (var entry : sortedLinkedHashMap.entrySet()) System.out.println(entry.getKey() + ": " + entry.getValue()); | |
} | |
private static Map<String, Integer> sortHashMap(Map<String, Integer> unsortedMap) { | |
// Create a sorted SET | |
SortedSet<Map.Entry<String, Integer>> sortedSet = new TreeSet<>((e1, e2) -> { | |
int res = e1.getValue().compareTo(e2.getValue()); | |
if (res == 0) | |
return e1.getKey().compareTo(e2.getKey()); | |
return res * -1; | |
}); | |
// Fill the sorted SET with the unsorted MAP | |
// At this point, it is sorted | |
sortedSet.addAll(unsortedMap.entrySet()); | |
// Now put it in a Linked Hash Map if you really need a MAP instead of a SET | |
Map<String, Integer> sortedLinkedHashMap = new LinkedHashMap<>(); | |
for (var entry : sortedSet) sortedLinkedHashMap.put(entry.getKey(), entry.getValue()); | |
// Return it | |
return sortedLinkedHashMap; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment