A brief talk on the map of Java by value (map sort through value) _java

Source: Internet
Author: User
Tags comparable data structures set set in python

A map is a collection of key-value pairs, also called a dictionary or associative array, and is one of the most common data structures. How do you get a map sorted by value in Java? It seems simple, but it's not easy!

For example, the key in the map is a string that represents a word, and value is an int that represents the number of times the word appears, and now we want to sort by the number of occurrences of the word:

Map map = new TreeMap ();
Map.put ("Me", 1000);
Map.put ("and", 4000);
Map.put ("You", 3000);
Map.put ("Food", 10000);
Map.put ("Hungry", 5000);
Map.put ("later", 6000);

The results sorted by value should be:

Key value
me 1000 you
3000 and
4000
hungry 5000
later 6000 food 10000

First, the SORTEDMAP structure cannot be used because the SORTEDMAP is a key-sorted map, not a map sorted by value, and we want a map sorted by value.

Couldn ' t you doing this with a sortedmap?
No, because the map are being sorted by its keys.

Method One:

The following Java code:

Import Java.util.Iterator;
Import Java.util.Set;

Import Java.util.TreeSet;
    public class Main {public static void main (string[] args) {Set set = new TreeSet ();

    Set.add (New Pair ("Me", "1000"));
    Set.add (New Pair ("and", "4000"));

    Set.add (New Pair ("You", "3000"));
    Set.add (New Pair ("Food", "10000"));

    Set.add (New Pair ("Hungry", "5000"));
    Set.add (New Pair ("later", "6000"));

    Set.add (New Pair ("Myself", "1000"));

      for (Iterator i = Set.iterator (); I.hasnext ();)
  System.out.println (I.next ());
  } class Pair implements comparable {private final String name;

  private final int number;
    Public Pair (String name, int number) {this.name = name;
  This.number = number;
    Public Pair (string name, string number) throws NumberFormatException {this.name = name;

  This.number = integer.parseint (number); public int compareTo (Object o) {if (o instanceof Pair) {int cmp = Double.compare (number, (Pair) o). Numbe
R);      if (CMP!= 0) {return CMP;
    Return Name.compareto ((Pair) O). Name;

  } throw new ClassCastException ("Cannot compare Pair with" + O.getclass (). GetName ());
  Public String toString () {return name + ' + ' + number;

 }
}

Similar C + + code:

typedef pair<string, int> pair;

int CMP (const pair& x, const pair& y)
{return
  x.second > y.second;
}

Map<string,int> m;
Vector<pair> Vec;
for (Map<wstring,int>::iterator Curr = M.begin (); Curr!= m.end (); ++curr)
{
  Vec.push_back make_pair ( Curr->first, Curr->second));
Sort (Vec.begin (), Vec.end (), CMP);

the real meaning of the above method is to encapsulate the key value pairs (map.entry) in the MAP structure into a custom class (struct), or directly with the map.entry class . Custom classes know how to sort themselves, that is, by value, specifically for themselves comparable interface or construct a Comparator object , and then use an ordered set without the map structure (SortedSet, TreeSet is an implementation of the sortedset ), so that the purpose of sort by value in the map is achieved. That is, instead of a Map, the map.entry is treated as an object, so the problem becomes an ordered collection of that object or a sort of collection of that object. You can use the sortedset so that nature is ordered after the insertion completes, or a list or array is used, and then sorted ( collections.sort ( ) or Arrays.sort () ).

Encapsulate the information in its own class. either implement
Comparable and write rules for the natural ordering or write a
Comparator based on your criteria. Store the information in a sorted
collection, or use the Collections.sort () method.

Method Two:

can also use the following code to sort by value:

public static map Sortbyvalue (map map) {List List = new LinkedList (Map.entryset ()); Collections.sort (list, new Comparator () {public int compare (object O1, Object O2) {return ((comparable) (

      (map.entry) (O1)). GetValue ()). CompareTo ((map.entry) (O2)). GetValue ());
    }
    });

    Map result = new Linkedhashmap (); for (Iterator it = List.iterator (); It.hasnext ();)
      {Map.entry Entry = (map.entry) it.next ();
    Result.put (Entry.getkey (), Entry.getvalue ());
  return result;
    public static map Sortbyvalue (map map, final Boolean reverse) {List List = new LinkedList (Map.entryset ());
          Collections.sort (list, new Comparator () {public int compare (object O1, Object O2) {if (reverse) {
        Return-((comparable) ((Map.entry) (O1)). GetValue ()). CompareTo ((map.entry) (O2)). GetValue ()); Return ((comparable) (Map.entry) (O1). GetValue ()). CompareTo ((map.entry) (O2)). GetValue ());

    }
    });
    Map result = new Linkedhashmap (); for (Iterator it = List.iterator (); It.hasnext ();)
      {Map.entry Entry = (map.entry) it.next ();
    Result.put (Entry.getkey (), Entry.getvalue ());
  return result;
    }         map Map = new HashMap ();
    Map.put ("A", 4);
    Map.put ("B", 1);
    Map.put ("C", 3);
    Map.put ("D", 2);
    Map sorted = Sortbyvalue (map);
System.out.println (sorted);
    Output: {b=1, d=2, c=3, a=4} or you can do this: map map = new HashMap ();
    Map.put ("A", 4);
    Map.put ("B", 1);
    Map.put ("C", 3);

    Map.put ("D", 2); set<map.entry<string, integer>> treeSet = new treeset<map.entry<string, integer>> (New Com
              Parator<map.entry<string, integer>> () {public int compare (map.entry<string, integer> O1,
            Map.entry<string, integer> O2) {Integer D1 = O1.getvalue (); Integer D2 = O2.getValue ();

            int r = D2.compareto (D1);
            if (r!= 0) return R;
          else return O2.getkey (). CompareTo (O1.getkey ());
    }

        });
    Treeset.addall (Map.entryset ());
    System.out.println (TreeSet);

 Output: [A=4, C=3, d=2, B=1]

In addition, the implementation of sort map by value in Groovy is, of course, essentially the same, but concise:

Using the Sort method of map in groovy (which requires groovy 1.6),

def result = Map.sort () {A, B-> 
      B.value.compareto (a.value)
    }

Such as:

["A": 3, "B": 1, "C": 4, "D": 2].sort{a,b-> A.value-b.value}

The results are: [B:1, D:2, A:3, C:4]

Also similar in Python:

H = {"A": 2, "B": 1, "C": 3}
i = H.items ()//i = [(' A ', 2), (' C ', 3), (' B ', 1)]
I.sort (Lambda (k1,v1), (K2,V2): CMP (v2 , v1))//I = [(' C ', 3], (' A ', 2), (' B ', 1)]

The above article on the Java map by value sorting (map sort by values) is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.