TreeMap的排序功能,構造方法


/**
 *    /*
         * 練習二:
         * 學生對象(姓名,年齡)都有自己的歸屬地,既然有對應關系。
         * 將學生對象和歸屬地存儲到map集合中。
         * 注意:同姓名同年齡視為重復的鍵。

                      按照學生的年齡進行從小到大的排序。 
         * 如果要對學生按照姓名排序呢?
       
 */
public class Practise2 {

    public static void main(String[] args) {
        /*創建Map集合*/
        Map<Student,String> classMap = new HashMap<Student,String>();
        classMap.put(new Student("小明",15), "上海");
        classMap.put(new Student("小李",15), "沈陽");
        classMap.put(new Student("小徐",13), "武漢");
        classMap.put(new Student("小明",15), "上海");        //視為重復的鍵
        classMap.put(new Student("天天",14), "武漢");
        classMap.put(new Student("剛剛",12), "河北");
        
        /*排序,想到treeSet,比較簡單,按姓名排序,按年齡為自然排序*/
        Map<Student,String> classTreeMap = new TreeMap<Student,String>(new Comparator<Student>() {

            @Override
            public int compare(Student o1, Student o2) {
                int temp = o1.getName().compareTo(o2.getName());
                return temp==0?o1.compareTo(o2):temp;
            }
        });
        classTreeMap.put(new Student("小明",15), "上海");
        classTreeMap.put(new Student("小李",15), "沈陽");    
        classTreeMap.put(new Student("小徐",13), "武漢");
        classTreeMap.put(new Student("小明",15), "上海");        //視為重復的鍵
        classTreeMap.put(new Student("天天",14), "武漢");
        classTreeMap.put(new Student("剛剛",12), "河北");

        for(Student stu : classTreeMap.keySet()){
            System.out.println(stu);
        }
        
        /*Map轉成List的辦法*/
        List<Map.Entry<Student, String>> list = new ArrayList<Map.Entry<Student, String>>(classTreeMap.entrySet());

        for(Entry ent: list){
            System.out.println(ent.getKey());
            System.out.println(ent.getValue());
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM