There are two ways to get the key and value of the map:
map.keySet(): First obtain the key of the map, and then obtain the corresponding value according to the key;
map..entrySet(): query the key and value of the map at the same time, only need to query once;
For a performance comparison of the two, see the comparison of map.keySet() and map.EntrySet() .
The following is to get the key and value of the map, and the elements in the map are compared and sorted by key or value;
Note: When the value of the map is equal, it is sorted according to the key value
public class MapSort {
public static void main(String[] args) {
Map<String,String> map = new HashMap<String,String>();
map.put("b","4");
map.put("a","5");
map.put("c","3");
map.put("d","5");
//通过map.keySet()方法
//方法一:通过得到key的值,然后获取value;
/*for(String key : map.keySet()){
String value = map.get(key);
System.out.println(key+" "+value);
}*/
//使用迭代器,获取key;
/*Iterator<String> iter = map.keySet().iterator();
while(iter.hasNext()){
String key=iter.next();
String value = map.get(key);
System.out.println(key+" "+value); //through the map.entrySet() method
}*/
//Method 1: Loop each key-value pair in the map, and then get the key and value
/*for(Entry<String, String> vo : map.entrySet()){
vo.getKey();
vo.getValue( );
System.out.println(vo.getKey()+" "+vo.getValue());
}*/
/*//Use iterator to get key
Iterator<Entry<String,String>> iter = map. entrySet().iterator();
while(iter.hasNext()){
Entry<String,String> entry = iter.next();
String key = entry.getKey();
String value = entry.getValue();
System .out.println(key+" "+value);
}*/
//Convert map<String,String> to ArryList, but the elements in the list are Entry<String,String>
List<Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(map.entrySet());
Collections.sort(list,new Comparator<Entry<String,String>>(){
@Override
public int compare(Entry<String, String> o1,
Entry<String, String> o2) {
int flag = o1.getValue().compareTo(o2.getValue());
if(flag==0){
return o1.getKey().compareTo(o2.getKey());
}
return flag;
}
});
//遍历list得到map里面排序后的元素
for(Entry<String, String> en : list){
System.out.println(en.getKey()+" "+en.getValue());
}
}
}