Skip to content

Commit 8b41d10

Browse files
committed
Comparable Generics TreeMap
1 parent 573b802 commit 8b41d10

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

Collection/Map/src/ex06/.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
/ComparableTreeMap.class
2+
/ComparableTreeMap$1.class
3+
/Main.class
4+
/ComparableGenericsTreeMap$1.class
5+
/ComparableGenericsTreeMap.class
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package ex06;
2+
3+
import java.util.Comparator;
4+
import java.util.HashMap;
5+
import java.util.Map;
6+
import java.util.SortedSet;
7+
import java.util.TreeSet;
8+
9+
// https://stackoverflow.com/questions/2864840/treemap-sort-by-value
10+
11+
public class ComparableGenericsTreeMap {
12+
13+
static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
14+
15+
SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>( new Comparator<Map.Entry<K,V>>() {
16+
17+
@Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
18+
int res = e1.getValue().compareTo(e2.getValue());
19+
return res != 0 ? res : 1; // Special fix to preserve items with equal values
20+
}
21+
}
22+
);
23+
24+
sortedEntries.addAll(map.entrySet());
25+
return sortedEntries;
26+
}
27+
28+
}
29+
30+
31+
32+
class Main {
33+
34+
public static void main(String[] args) {
35+
36+
// now with Integer
37+
38+
Map<String, Integer> nonSortedMap = new HashMap<String, Integer>();
39+
nonSortedMap.put("ape", 1);
40+
nonSortedMap.put("pig", 3);
41+
nonSortedMap.put("cow", 1);
42+
nonSortedMap.put("frog", 2);
43+
44+
ComparableGenericsTreeMap comparableTreeMap = new ComparableGenericsTreeMap();
45+
46+
47+
System.out.println(comparableTreeMap.entriesSortedByValues(nonSortedMap));
48+
49+
// now with String
50+
51+
Map<String, String> nonSortedMap2 = new HashMap<String, String>();
52+
nonSortedMap2.put("ape", "a");
53+
nonSortedMap2.put("pig", "x");
54+
nonSortedMap2.put("cow", "v");
55+
nonSortedMap2.put("frog", "a");
56+
57+
ComparableGenericsTreeMap comparableTreeMap2 = new ComparableGenericsTreeMap();
58+
59+
60+
System.out.println(comparableTreeMap2.entriesSortedByValues(nonSortedMap2));
61+
62+
}
63+
64+
}

0 commit comments

Comments
 (0)