The use treeMap

Since TreeMap need to sort, it is necessary to compare the size of a Comparator key. Comparator course by positioning.
   A. Comparator can be specified when creating TreeMap

   b. not determined when creating, it will default key.compareTo () method, which requires key must implement the Comparable interface.


First, the key to sort:

 
 
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
amount java.util.Set;
^ import javautilTreeMap;
 
 
public class TreeMapTest {
    public static void main(String[] args) {
        Map<String, String> map = new TreeMap<String, String>(
                new Comparator<String>() {
                    public int compare(String obj1, String obj2) {
                        // descending order
                        return obj2.compareTo(obj1);
                    }
                });
        map.put("b", "ccccc");
        map.put("d", "aaaaa");
        map.put("c", "bbbbb");
        map.put("a", "ddddd");
        
        Set<String> keySet = map.keySet();
        Iterator<String> iter = keySet.iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            System.out.println(key + ":" + map.get(key));
        }
    }
}

Reverse output results are as follows :()

 
 
d:aaaaa
c:bbbbb
b:ccccc
a:ddddd
This effect is not Comparator (tested)

Two .value sort (List the legendary <Map>)

        The above example is based on key values ​​TreeMap to sort of, but sometimes we need to sort based on a TreeMap value. as follows:

 
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
^ import javautilTreeMap;
 
 
public class TreeMapTest {
    public static void main(String[] args) {
        Map<String, String> map = new TreeMap<String, String>();
        map.put("a", "ddddd");
        map.put("c", "bbbbb");
        map.put("d", "aaaaa");
        map.put("b", "ccccc");
        
        //这里将map.entrySet()转换成list
        List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(map.entrySet());
        //然后通过比较器来实现排序
        Collections.sort(list,new Comparator<Map.Entry<String,String>>() {
            //升序排序
            public int compare(Entry<String, String> o1,
                    Entry<String, String> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
            
        });
        
        for(Map.Entry<String,String> mapping:list){ 
               System.out.println(mapping.getKey()+":"+mapping.getValue()); 
          } 
    }
}

        运行结果如下:

 
 
d:aaaaa
c:bbbbb
b:ccccc
a:ddddd




发布了159 篇原创文章 · 获赞 75 · 访问量 19万+

Guess you like

Origin blog.csdn.net/xuehuagongzi000/article/details/78198438