1

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.

user326667
  • 509
  • 1
  • 7
  • 11
  • do you want to sort the values or the map - that is, do you want future calls to, say, `keySet()` to return in sorted order, or do you just want a temporarily sorted view of the values? – Carl May 22 '10 at 20:09

2 Answers2

4

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.

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
  • the ordering class returns a list, how to create an ImmutableSortedMap from this list? – user326667 May 23 '10 at 10:24
  • @chris-gr: You can't have a `SortedMap` 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>` – polygenelubricants May 23 '10 at 11:31
-3

Collections.sort(map.values(), myComparator); Create myComparator as Comparator to compare the B objects by the double field.

duduamar
  • 3,816
  • 7
  • 35
  • 54