Method to sort any map with numeric value from greatest to least.

Discussion in 'Resources' started by Barinade, Mar 14, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    Barinade

    Code:
        private static Map<?, ?> sort(final Map<?, ? extends Number> map) {
            String s= null;
            Comparator c = new Comparator<Object>() {
                @Override
                public int compare(Object a, Object b) {
                    if (map.get(a).doubleValue() >= map.get(b).doubleValue()) {
                        return -1;
                    } else {
                        return 1;
                    }
                }
            };
            TreeMap<Object, Object> tm = new TreeMap<Object , Object>(c);
            tm.putAll((Map<Object, ? extends Number>) map);
            return (Map<Object, Object>) tm;
        }
    Very interested in a better way to do this if anyone has one.

    Usage
    Code:
    Map<String, Integer> map = new HashMap<String, Integer>();
    //put some map sets
    map = sort(map); //cast needed, you got this.
    Test outputs
    Code:
    Five: 5 Three: 3 One: 1 Two: 2 Four: 4 unsorted
    Five: 5 Four: 4 Three: 3 Two: 2 One: 1 sorted
    1.1 double: 1.1 2.2 double: 2.2 4.4 double: 4.4 5.5 double: 5.5 3.3 double: 3.3 unsorted
    5.5 double: 5.5 4.4 double: 4.4 3.3 double: 3.3 2.2 double: 2.2 1.1 double: 1.1 sorted
    5.5 float: 5.5 2.2 float: 2.2 1.1 float: 1.1 3.3 float: 3.3 4.4 float: 4.4 unsorted
    5.5 float: 5.5 4.4 float: 4.4 3.3 float: 3.3 2.2 float: 2.2 1.1 float: 1.1 sorted
    for least to greatest, change
    Code:
                    if (map.get(a).doubleValue() >= map.get(b).doubleValue()) {
                        return -1;
                    } else {
                        return 1;
                    }
    to
    Code:
                    if (map.get(a).doubleValue() >= map.get(b).doubleValue()) {
                        return 1;
                    } else {
                        return -1;
                    }
     
  2. Offline

    Garris0n

    Probably worth noting that if you're using a list you can use Collections.sort().
     
  3. Offline

    TheE

    Bukkit bundles Guava, so you can just do the whole thing in two lines:
    Code:java
    1. valueComparator =Ordering.natural().onResultOf(Functions.forMap(map));
    2. map =ImmutableSortedMap.copyOf(myOriginalMap, valueComparator);
    3.  

    Sorting the Map live is a bit more advanced, but also easily possible as shown in this answer on stackoverflow (where I also happen to copy the above examples from).
     
Thread Status:
Not open for further replies.

Share This Page