Java TreeMap使用方法


1、使用默認的TreeMap 構造函數,其中key值需要有比較規則。

2、使用默認的TreeMap 構造函數,Key中添加自定義類型,自定義類型必須繼承Comparator。

3、使用比較器類來來實現排序,自定義類型不用來繼承Comparator

 

試例代碼:

 

public class Demo {

   public static void main(String[] args) {

   //1、使用默認的TreeMap 構造函數,其中key值需要有比較規則

   TreeMap<Integer, String> map =new TreeMap<>();

     map.put(new Integer(2), "BB");

   map.put(new Integer(1), "AA");

   map.put(new Integer(5), "EE");

   map.put(new Integer(3), "CC");

   map.put(new Integer(4), "DD");

   map.put(new Integer(2), "AA");   //驗證重復key是否能夠插入

     //使用遍歷EntrySet方式

   for(Entry<Integer, String> entry:map.entrySet()){

    System.out.println("Key:"+entry.getKey()+ " --- value:"+entry.getValue());

   }

      //2、使用默認的TreeMap 構造函數,Key中添加自定義類型,自定義類型必須繼承Comparator

   System.out.println("-------------------2、使用默認的TreeMap 構造函數,Key中添加自定義類型,自定義類型必須繼承Comparator-----------------------");

   TreeMap<person,String> mapPer=new TreeMap<>();

   mapPer.put(new person("張三",22), "6K");

   mapPer.put(new person("老王",35), "29K");

   mapPer.put(new person("小張",31), "11K");

         for(Entry<person, String> entry:mapPer.entrySet()){

    System.out.println("Key:"+entry.getKey()+ " --- value:"+entry.getValue());

   }

      //3、使用比較器類來來實現排序,自定義類型不用來繼承Comparator

   System.out.println("-------------------3、使用比較器類來來實現排序,自定義類型不用來繼承Comparator-----------------------");

   TreeMap<Book,String> mapBook =new TreeMap<>(new BookComparator());

   mapBook.put(new Book("流浪地球",60),"200頁");

   mapBook.put(new Book("三體",100),"400頁");

   mapBook.put(new Book("大秦帝國",180),"900頁");

      for(Entry<Book, String> entry:mapBook.entrySet()){

    System.out.println("Key:"+entry.getKey()+ " --- value:"+entry.getValue());

   }

   }   }

//自定義person類

class person implements Comparable<person> {

 String name;  int age;

   public person(String name,int age) {

   this.name=name;

   this.age=age;  }

   @Override

 public String toString() { 

    return "姓名:"+this.name +" 年齡:" +this.age;

 }

 @Override

 public int compareTo(person o) {

  if(o.age>this.age) {

   return 1;

  } else if(o.age<this.age) {

   return -1;

  }

  return 0;

 }  }

//自定義book類

class Book {

 String name;

 double price;

   public Book(String name,double price) {  

   this.name=name;

    this.price=price;  }

   @Override

 public String toString() {

  return "書名:"+this.name+" 價格:"+this.price;

 }  }

//book比較器類

class BookComparator implements Comparator<Book>{

 @Override

 public int compare(Book o1, Book o2) {

  if(o1.price>o2.price) {

   return 1;

  } else if(o1.price<o2.price) {

   return -1;

  }

  return 0;

 }  }

 


免責聲明!

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



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