As we all know, the map structure in Java is stored key-->value key value pairs, and according to the characteristics of the map, there are no two key elements in the same map, and value does not have this limitation. In other words, the key in the same map is unique, and value is not unique. Map is an interface, we can not directly declare a map type of objects, in practical development, the more commonly used map data structure is hashmap and treemap, they are direct subclasses of the map. If you take into account the access efficiency, it is recommended to use the HASHMAP data structure, and if you need to take into account the order of key, we recommend the use of TreeMap, but treemap in the deletion, add the process needs to sort, performance is poor.
sort with key
(1.1): We can declare a TreeMap object
Map<integer, person> map = new Treemap<integer, person> ()
(1.2):Then add the elements to the map and, by outputting the results, you can see that the elements in the map are sorted:
Iterate through the collection for
(iterator<integer> it = Map.keyset (). iterator (); It.hasnext ();) {Person of person
= Map.get (It.next ());
System.out.println (Person.getid_card () + "" + person.getname ());
}
(2):We can also declare a HashMap object and assign the HashMap object to TreeMap as follows:
Map<integer, person> map = new Hashmap<integer, person> ();
TreeMap TreeMap = new TreeMap (map);
Note: The above two ways teams can easily achieve the sort of key values.
Sort with value
(1): First declare a HashMap object:
map<string, integer> map = new hashmap<string, integer> ();
(2):Converts the MA collection to a list collection, and finally sorts with the collections tool class
list<entry<string,integer>> list = new arraylist<entry<string,integer>> (Map.entrySet ())
(3):Sorted by the Collections.sort (List list,comparator C) method, the code is as follows:
Collections.sort (list, new comparator<map.entry<string, integer>> () {public
int compare (map.entry <string, integer> O1,
map.entry<string, integer> O2) {return
(O2.getvalue ()-o1.getvalue ());
}
});
Note: This enables the value in the map to be sorted in reverse order, and if an ascending row is required, only modify O2.getvalue ()-o1.getvalue () to O1.getvalue ()-o2.getvalue ().
Article from: Past Memory: http://www.iteblog.com/archives/484