diff options
| author | ilotterytea <iltsu@alright.party> | 2024-10-17 22:37:53 +0500 |
|---|---|---|
| committer | ilotterytea <iltsu@alright.party> | 2024-10-17 22:37:53 +0500 |
| commit | 41fffc19a1bb8cfbe8d33dc6e6e5b5405472f02f (patch) | |
| tree | fbb45eb1666f73f9884e37041b6e68ff18da786b | |
| parent | 64c31f20f62316c17d22048d9a61f2af8458c782 (diff) | |
feat: comparator for sorting the map by values
| -rw-r--r-- | core/src/kz/ilotterytea/javaextra/comparators/MapValueKeyComparator.java | 20 |
1 files changed, 20 insertions, 0 deletions
diff --git a/core/src/kz/ilotterytea/javaextra/comparators/MapValueKeyComparator.java b/core/src/kz/ilotterytea/javaextra/comparators/MapValueKeyComparator.java new file mode 100644 index 0000000..d168cf8 --- /dev/null +++ b/core/src/kz/ilotterytea/javaextra/comparators/MapValueKeyComparator.java @@ -0,0 +1,20 @@ +package kz.ilotterytea.javaextra.comparators; + +import java.util.Comparator; +import java.util.Map; + + +// Cv pasted from https://stackoverflow.com/a/53081966 +public class MapValueKeyComparator<K extends Comparable<? super K>, V extends Comparable<? super V>> + implements Comparator<Map.Entry<K, V>> { + + public int compare(Map.Entry<K, V> a, Map.Entry<K, V> b) { + int cmp1 = b.getValue().compareTo(a.getValue()); //can reverse a and b position for ascending/descending ordering + if (cmp1 != 0) { + return cmp1; + } else { + return a.getKey().compareTo(b.getKey()); //can reverse a and b position for ascending/descending ordering + } + } + +} |
