• Map sorted by Key


    why comparator ?

    • comparable : adj

    • comparator : n

    Some class can't be changed , which like Map , Set and their subclass . They are given being unchangeable . Thus , we can't

    public TreeMap implements comparable{
    ...
    }
    

    So , here comparator works .

    // mapCompare is the class with comparator()
    TreeMap<String,Integer> map = new TreeMap<String,Integer>( new mapCompare() ); 
    
    // The configure  <String>  is same as the key of *TreeMap*
    class mapCompare implements Comparator<String > {
    public int compare( String o1, String o2){
       o1.compareTo(o2);
    }
    

    Code

    import java.util.Comparator;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.TreeMap;
    
    public class mapSortedByKey {
    	public static void main(String[] args) {
    		
    		// New one map
    		
    		TreeMap<String, Integer> map = new TreeMap<String, Integer>(new mapCompare());
    		map.put("E", 1);
    		map.put("A", 2);
    		map.put("B", 3);
    		map.put("C", 4);
    		map.put("D", 5);
    		
    		// print 
    		/*for( Map.Entry<String,Integer> one: map.entrySet() ){
    			System.out.println(one.getKey()+":"+one.getValue());
    		}
    		*/
    		
    		Iterator<Map.Entry<String,Integer> > iter = map.entrySet().iterator();
    		while(iter.hasNext()){
    			Map.Entry<String,Integer> one = iter.next();
    			System.out.println(one.getKey() +": "+one.getValue());
    		}
    	}
    }
    
    class mapCompare implements Comparator<String> {
    	public int compare(String o1, String o2) {
    		return o2.compareTo(o1);
    	}
    }
    
    E: 1
    D: 5
    C: 4
    B: 3
    A: 2
    
  • 相关阅读:
    Socket通信
    浏览器调用打印机
    python dict操作
    python list操作
    python 模块Example链接
    python random模块
    python configparser模块
    python unittest模块
    python timeit模块
    python datetime模块
  • 原文地址:https://www.cnblogs.com/cyno/p/4451768.html
Copyright © 2020-2023  润新知