Line | |
---|
1 | package geniusweb.bagga.dicehaggler;
|
---|
2 |
|
---|
3 | import java.util.SortedSet;
|
---|
4 | import java.util.TreeMap;
|
---|
5 | import java.util.TreeSet;
|
---|
6 |
|
---|
7 | public final class RankableMap<K extends Comparable<K>, V extends Comparable<V>> extends TreeMap<K, V> {
|
---|
8 |
|
---|
9 | /**
|
---|
10 | *
|
---|
11 | */
|
---|
12 | private static final long serialVersionUID = 1L;
|
---|
13 |
|
---|
14 | //https://stackoverflow.com/questions/28906249/how-can-i-rank-keys-in-a-treemap-by-their-values
|
---|
15 | private static final class Pair<K extends Comparable<K>, V extends Comparable<V>> implements Comparable<Pair<K, V>> {
|
---|
16 | private final K k;
|
---|
17 | private final V v;
|
---|
18 | private Pair(K k, V v) {
|
---|
19 | this.k = k;
|
---|
20 | this.v = v;
|
---|
21 | }
|
---|
22 | @Override
|
---|
23 | public int compareTo(Pair<K, V> that) {
|
---|
24 | int a = v.compareTo(that.v);
|
---|
25 | return a != 0 ? a : k.compareTo(that.k);
|
---|
26 | }
|
---|
27 | }
|
---|
28 |
|
---|
29 | private final SortedSet<Pair<K, V>> set = new TreeSet<>();
|
---|
30 |
|
---|
31 | @Override
|
---|
32 | public V put(K k, V v) {
|
---|
33 | V v2 = super.put(k, v);
|
---|
34 | if (v.equals(v2))
|
---|
35 | return v2;
|
---|
36 | if (v2 != null)
|
---|
37 | set.remove(new Pair<>(k, v2));
|
---|
38 | set.add(new Pair<>(k, v));
|
---|
39 | return v2;
|
---|
40 | }
|
---|
41 |
|
---|
42 | @Override
|
---|
43 | public V remove(Object k) {
|
---|
44 | V v = super.remove(k);
|
---|
45 | if (v != null)
|
---|
46 | set.remove(new Pair<>((K) k, v));
|
---|
47 | return v;
|
---|
48 | }
|
---|
49 |
|
---|
50 | @Override
|
---|
51 | public void clear() {
|
---|
52 | super.clear();
|
---|
53 | set.clear();
|
---|
54 | }
|
---|
55 |
|
---|
56 | public int rank(K k) {
|
---|
57 | return 1 + set.headSet(new Pair<K, V>(k, get(k))).size();
|
---|
58 | }
|
---|
59 | } |
---|
Note:
See
TracBrowser
for help on using the repository browser.