How to sort a map(?,B) on the values in Java with google collections ordering function, if B is a class, which has a field of type double, which should be used for ordering.
views:
77answers:
2
A:
Collections.sort(map.values(), myComparator); Create myComparator as Comparator to compare the B objects by the double field.
duduamar
2010-05-22 19:51:04
-1 Collections.sort(..) requires a List while map.values() returns a Collection. This won't compile.
Willi
2010-05-22 22:01:10
+1
A:
Here's a snippet that uses a generic method that takes a Map<K,V>
and a Comparator<? super V>
, and returns a SortedSet
of its entrySet()
sorted on the values using the comparator.
public class MapSort {
static <K,V> SortedSet<Map.Entry<K,V>>
entriesSortedByValues(Map<K,V> map, final Comparator<? super V> comp) {
SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
new Comparator<Map.Entry<K,V>>() {
@Override public int compare(Entry<K, V> e1, Entry<K, V> e2) {
return comp.compare(e1.getValue(), e2.getValue());
}
}
);
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
static class Custom {
final double d; Custom(double d) { this.d = d; }
@Override public String toString() { return String.valueOf(d); }
}
public static void main(String[] args) {
Map<String,Custom> map = new HashMap<String,Custom>();
map.put("A", new Custom(1));
map.put("B", new Custom(4));
map.put("C", new Custom(2));
map.put("D", new Custom(3));
System.out.println(
entriesSortedByValues(map, new Comparator<Custom>() {
@Override public int compare(Custom c1, Custom c2) {
return Double.compare(c1.d, c2.d);
}
})
); // prints "[A=1.0, C=2.0, D=3.0, B=4.0]"
}
}
On Google Ordering
public static <T> Ordering<T> from(Comparator<T> comparator)
Returns an ordering for a pre-existing comparator.
The above solution uses a Comparator
, so you can easily use the above method to use Ordering
instead.
polygenelubricants
2010-05-22 20:02:02
the ordering class returns a list, how to create an ImmutableSortedMap from this list?
2010-05-23 10:24:55
@chris-gr: You can't have a `SortedMap<K,V>` that sorts on `V`. That violates the `SortedMap` contract. See http://stackoverflow.com/questions/2864840/treemap-sort-by-value/ The best you can do is create an `ImmutableSortedSet` from a `SortedSet<Map.Entry<K,V>>`
polygenelubricants
2010-05-23 11:31:19