HashMap遍歷與按key排序。

2021-06-27 08:34:55 字數 1059 閱讀 6978

google搜尋 hashmap 遍歷 寫道

第一種: 

map map = new hashmap(); 

iterator iter = map.entryset().iterator(); 

while (iter.hasnext())  

效率高,以後一定要使用此種方式! 

第二種: 

map map = new hashmap(); 

iterator iter = map.keyset().iterator(); 

while (iter.hasnext())  

效率低,以後盡量少使用! 

關於hashmap 按value排序

最近開發中用到了hashmap ,而且想到要利用其value的大小排序。。真是個傷腦筋的問題。

還好,經過查閱各個地方的資料。發現這個下邊的**處理是最簡單有效的。**很少,卻達到目的了。

一般我堅持的乙個原則的是:能簡單處理的,盡量不做複雜工作。

關鍵**部分如下:

hashmap map_data=new hashmap();

map_data.put("a", "98");

map_data.put("b", "50");

map_data.put("c", "50");

map_data.put("d", "25");

map_data.put("e", "85");

system.out.println(map_data);

list> list_data = new arraylist>(map_data.entryset());

collections.sort(list_data, new comparator>()

else }

});system.out.println(list_data);

主要的乙個知識點在這個collections.sort(list,comparator介面實現)地方,而最最重要核心部分是這個comparator實現。因為comparator實現決定你的排序。採用了隱藏類實現方式。

Lambda表示式對HashMap按值排序

使用lambda表示式對hashmap按value物件的時間屬性進行降序排序 hashmap usermap newhashmap usermap.put 1,newuser 張三 8 new date gettime usermap.put 2,newuser 李四 10 new date get...

STL之map按key排序與按value排序

如下 include include include include using namespace std typedef pair int fre bool comless const fre a,const fre b bool comgreater const fre a,const fre...

字典序排數 與dfs遍歷N叉樹

題目如下 給定乙個整數 n,返回從 1 到 n 的字典順序。例如,給定 n 1 3,返回 1,10,11,12,13,2,3,4,5,6,7,8,9 請盡可能的優化演算法的時間複雜度和空間複雜度。輸入的資料 n 小於等於 5,000,000。首先觀察數字的排列規則,會發現這是乙個n叉樹的前序遍歷.子...