Android to implement the HashMap sorting method
- 2020-06-07 05:16:39
- OfStack
HashMap sorting is a common sorting algorithm in data structure and algorithm. This paper takes Android platform as an example to implement the algorithm.
The specific code is as follows:
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("lisi", 5);
map.put("lisi1", 1);
map.put("lisi2", 3);
map.put("lisi3", 9);
List<Map.Entry<String, Integer>> infoIds = new ArrayList<Map.Entry<String, Integer>>(
map.entrySet());
System.out.println("-------------- Before ordering --------------");
for (int i = 0; i < infoIds.size(); i++) {
String id = infoIds.get(i).toString();
System.out.println(id);
}
// The sorting
Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1,
Map.Entry<String, Integer> o2) {
return ( o1.getValue()-o2.getValue());
}
});
System.out.println("-------------- After ordering --------------");
for (int i = 0; i < infoIds.size(); i++) {
Entry<String,Integer> ent=infoIds.get(i);
System.out.println(ent.getKey()+"="+ent.getValue());
}
}
I hope the HashMap sorting algorithm described in this paper can be helpful to your algorithm learning.