As we all know, the map structure in Java is stored in the Key->value key value pair, and according to the map, there is no two key element in the same map, and value does not exist. In other words, the key is unique in the same map, and value is not unique. Map is an interface, we can not directly declare a map type of object, in the actual development, the more commonly used map data structure is hashmap and treemap, they are direct sub-class map. If the access efficiency is considered, 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 need to sort, poor performance.
- sort by Key
we can declare a TreeMap object
Map<Integer, Person> map = new TreeMap<Integer, Person>(); |
Then add the elements to the map, and you can see that the elements in the map are all sorted by the output.
//遍历集合 for (Iterator<Integer> it = map.keySet().iterator(); it.hasNext();) { Person person = map.get(it.next()); System.out.println(person.getId_card() + " " + person.getName()); } |
We can also declare a HashMap object, and then assign the HashMap object to TreeMap, as follows:
Map<Integer, Person> map = new HashMap<Integer, Person>(); TreeMap treemap = new TreeMap(map); |
- sort by Value
declare a HashMap object first:
Map<String, Integer> map = new HashMap<String, Integer>(); |
Then we can convert the map collection into a list collection, and list uses ArrayList to do the following:
List<Entry<String,Integer>> list = new ArrayList<Entry<String,Integer>>(map.entrySet()); |
Finally, the Collections.sort (List L, Comparator C) method is used to sort the code as follows:
collectio Ns.sort (list, new comparator<map.entry< String, integer>> () { &NBSP;&NBSP;&NBSP;&NBSP; public int compare (map.entry<string, integer> O1, Map.Entry <string, integer> O2) { return (O2.getvalue ()-o1.getvalue ()); &NBSP;&NBSP;&NBSP;&NBSP; } }); |
The above code is to say that the value in map is sorted in reverse order, if you need to sort in ascending order, only need to modify O2.getvalue ()-O1.getvalue () is O1.getvalue ()-O2.getvalue () can
In Java, map is sorted based on key value (key) or value