更新時間:2020-05-25 16:10:24 來源:動力節點 瀏覽2195次
使用默認的TreeMap 構造函數,其中key值需要有比較規則。
使用默認的TreeMap 構造函數,Key中添加自定義類型,自定義類型必須繼承Comparator。
使用比較器類來來實現排序,自定義類型不用來繼承Comparator
試例代碼:
public?class?Demo?{
???public?static?void?main(String[]?args)?{
???//1、使用默認的TreeMap?構造函數,其中key值需要有比較規則
???TreeMap?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?entry:map.entrySet()){
????System.out.println("Key:"+entry.getKey()+?"?---?value:"+entry.getValue());
???}
??????//2、使用默認的TreeMap?構造函數,Key中添加自定義類型,自定義類型必須繼承Comparator
???System.out.println("-------------------2、使用默認的TreeMap?構造函數,Key中添加自定義類型,自定義類型必須繼承Comparator-----------------------");
???TreeMap?mapPer=new?TreeMap<>();
???mapPer.put(new?person("張三",22),?"6K");
???mapPer.put(new?person("老王",35),?"29K");
???mapPer.put(new?person("小張",31),?"11K");
?????????for(Entry?entry:mapPer.entrySet()){
????System.out.println("Key:"+entry.getKey()+?"?---?value:"+entry.getValue());
???}
??????//3、使用比較器類來來實現排序,自定義類型不用來繼承Comparator
???System.out.println("-------------------3、使用比較器類來來實現排序,自定義類型不用來繼承Comparator-----------------------");
???TreeMap?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?entry:mapBook.entrySet()){
????System.out.println("Key:"+entry.getKey()+?"?---?value:"+entry.getValue());
???}
???}???}
//自定義person類
class?person?implements?Comparable?{
?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{
?@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;
?}??}
Java技術相關內容
Java TreeMap排序:http://m.dabaquan.cn/tutorial_java_advance/609.html
以上就是動力節點java培訓機構的小編針對“Java技術分享,treemap使用方法”的內容進行的回答,希望對大家有所幫助,如有疑問,請在線咨詢,有專業老師隨時為你服務。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習