HashMap storage is not ordered, but realized in accordance with the HashCode key.
Key = mobile phone brand, value = price, to achieve here and Sort by price Sort by name to this example.
Map phone=new HashMap(); phone.put("Apple",8899); phone.put("SAMSUNG",7000); phone.put("Meizu",2698); phone.put("Xiaomi",1800); System.out.println(phone);
Direct output HashMap obtained an unordered Map (not Arraylist reservoir type in that order)
1. Sort by key
Sort of name, you must first get the set (keySet) in bonds HashMap, and converted to an array, in order to sort by Arrays.sort ()
Set set=phone.keySet(); Object[] arr=set.toArray(); Arrays.sort(arr); for(Object key:arr){ System.out.println(key); }
Get sorted key
Finally HashMap.get (key) corresponding to the key value to give
for(Object key:arr){ System.out.println(key+": "+phone.get(key)); }
The result of printing
2. Sort by value
Sort price, need to be first in view HashMap (the entrySet) comprising mapping relationship,
as shown:
The entrySet convert List, and then rewrite the comparator compares can here be used List.sort (comparator), may also be used Collections.sort (list, comparator)
Converted to a list
List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(phone.entrySet()); //转换为list
Use list.sort () to sort
list.sort(new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return o2.getValue().compareTo(o1.getValue()); } });
Use Collections.sort () to sort
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return o2.getValue().compareTo(o1.getValue()); } });
Two ways result output
//for循环 for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i).getKey() + ": " + list.get(i).getValue()); } //for-each循环 for (Map.Entry<String, Integer> mapping : list){ System.out.println(mapping.getKey()+": "+mapping.getValue()); }
Traversal printout
//for for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i).getKey() + ": " +list.get(i).getValue()); } System.out.println(); //for-each for (Map.Entry<String, Integer> mapping : list) { System.out.println(mapping.getKey() + ": " +mapping.getValue()); }
result