導航:首頁 > 編程語言 > javahashmap排序value

javahashmap排序value

發布時間:2022-12-18 00:05:25

『壹』 如何對HashMap中的元素進行排序

HashMap是無序的集合,對裡面的元素進行排序,需要藉助其他有序的集合

參考代碼

importjava.util.HashMap;
//java8流處理
publicclassDemo1{
publicstaticvoidmain(String[]args){
HashMap<String,Integer>map=newHashMap<>();
map.put("lucy",76);
map.put("tom",92);
map.put("jack",86);
//按照Key(名字)進行排序,並列印
map.entrySet().stream().sorted((e1,e2)->e1.getKey().compareTo(e2.getKey())).forEach(System.out::println);
System.out.println("-------分割線----------");
//按照value(分數)進行排序,並列印
map.entrySet().stream().sorted((e1,e2)->e1.getValue().compareTo(e2.getValue())).forEach(System.out::println);

}
}

『貳』 hashmap按value排序


import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortHashMap {
public static void main(String[] args) {
//產生一個map並添加一些參數
Map<String, Integer> map = new HashMap<>();
map.put("ddd", 1);
map.put("aaa", 2);
map.put("bbb", 3);
map.put("ccc", 4);
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
//將map的entryset放入list集合
// 對list進行排序,並通過Comparator傳入自定義的排序規則
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o1.getValue() - o2.getValue(); //重寫排序規則,小於0表示升序,大於0表示降序
}
});
//用迭代器對list中的鍵值對元素進行遍歷
Iterator<Map.Entry<String, Integer>> iter = list.iterator();
while (iter.hasNext()) {
Map.Entry<String, Integer> item = iter.next();
String key = item.getKey();
int value = item.getValue();
System.out.println("鍵" + key + "值" + value);
}
}
}


如滿意,請採納

『叄』 java hashmap按照value來排序

ArrayList<Entry<String,String>> list = new ArrayList<Entry<String,String>>(sMap.entrySet());

Collections.sort(list, new Comparator<Object>(){
public int compare(Object e1, Object e2){
int v1 = Integer.parseInt(((Entry<String,String>)e1).getValue().toString());
int v2 = Integer.parseInt(((Entry)e2).getValue().toString());
return v1-v2;

}
});

for (Entry<String, String> e: l){
System.out.println(e.getKey()+" "+e.getValue());
}

閱讀全文

與javahashmap排序value相關的資料

熱點內容
dvd光碟存儲漢子演算法 瀏覽:757
蘋果郵件無法連接伺服器地址 瀏覽:963
phpffmpeg轉碼 瀏覽:672
長沙好玩的解壓項目 瀏覽:145
專屬學情分析報告是什麼app 瀏覽:564
php工程部署 瀏覽:833
android全屏透明 瀏覽:737
阿里雲伺服器已開通怎麼辦 瀏覽:803
光遇為什麼登錄時伺服器已滿 瀏覽:302
PDF分析 瀏覽:486
h3c光纖全工半全工設置命令 瀏覽:143
公司法pdf下載 瀏覽:382
linuxmarkdown 瀏覽:350
華為手機怎麼多選文件夾 瀏覽:683
如何取消命令方塊指令 瀏覽:350
風翼app為什麼進不去了 瀏覽:779
im4java壓縮圖片 瀏覽:362
數據查詢網站源碼 瀏覽:151
伊克塞爾文檔怎麼進行加密 瀏覽:893
app轉賬是什麼 瀏覽:163