treemap是可以根據鍵對map進行排序的,注意:是根據鍵。
一般來講,鍵可以使integer或者是string,
但是也可以是物件,但是該物件的實現類必須實現comparable介面。
class mycompare implements comparable
@override
public string tostring() ';
}public int getage()
public void setage(int age)
public string getname()
public void setname(string name)
@override
public int compareto(mycompare o)
}public class treemapandset
}}
輸出:鍵:people-----值:1
鍵:people-----值:2
鍵:people-----值:5
鍵:people-----值:3
鍵:people-----值:4
想想用這樣的方法對值進行排序就很簡單了,再來乙個hashmap即可。
另外,如果mycompare沒有實現comparable介面,也可以這樣子寫:
class mycompare
@override
public string tostring() ';
}public int getage()
public void setage(int age)
public string getname()
public void setname(string name)
}public class treemapandset
});treemap2.put(new mycompare(1,"first"),1);
treemap2.put(new mycompare(2,"second"),2);
treemap2.put(new mycompare(4,"fourth"),3);
treemap2.put(new mycompare(5,"fifth"),4);
treemap2.put(new mycompare(3,"third"),5);
for(map.entryentry :treemap2.entryset())
/*mapmap1 = new treemap<>();
map1.put(new mycompare(1,"first"),1);
map1.put(new mycompare(2,"second"),2);
map1.put(new mycompare(4,"fourth"),3);
map1.put(new mycompare(5,"fifth"),4);
map1.put(new mycompare(3,"third"),5);
for(map.entryentry :map1.entryset())*/
}}
輸出一樣。
另外來乙個直接對值進行排序的方法,也是不用實現comparator的:
class mycompare
@override
public string tostring() ';
}public int getage()
public void setage(int age)
public string getname()
public void setname(string name)
}public class treemapandset
});/* for(int i=0;ie:list)
}}
輸出:1----people
2----people
4----people
3----people
5----people
Map 排序 TreeMap 陷阱
hashmap的基於hash表的實現機制決定了他非常快的檢索速度,但也定了 不能排序 的標牌,工作中如果需要排序就要使用treemap treemap是可排序map,可對ke進行排序,那麼,是不是任何我們原來使用hashmap實現的業務都能使用treemap進行替換排序呢?答案是 否 原因在於,它們...
對map集合進行排序
在講解map排序之前,我們先來稍微了解下map。map是鍵值對的集合介面,它的實現類主要包括 hashmap treemap hashtable linkedhashmap。其中這四者的區別如下 簡單介紹 hashmap 我們最常用的map,它根據key的hashcode值來儲存資料,根據key可以...
對map集合進行排序
今天做統計時需要對x軸的地區按照地區 areacode 進行排序,由於在構建xmldata使用的map來進行資料統計的,所以在統計過程中就需要對map進行排序。在講解map排序之前,我們先來稍微了解下map。map是鍵值對的集合介面,它的實現類主要包括 hashmap,treemap,hashtab...