HashMap根据value值排序
生活随笔
收集整理的這篇文章主要介紹了
HashMap根据value值排序
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
/**
* hashMap排序
* @author lizhibiao
* @date 2018/12/3 11:47
*/
public class TestHashMapCollections
{
public static void main(String[] args)
{
Map<String, Integer> map = new HashMap<>();
map.put("王二", 8);
map.put("沈吳", 2);
map.put("小菜", 3);
map.put("大鳥(niǎo)", 1);
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
for (Map.Entry s : entrySet)
{
System.out.println(s.getKey()+"--"+s.getValue());
}
System.out.println("============排序后============");
//借助list實(shí)現(xiàn)hashMap排序//
//注意 ArrayList<>() 括號(hào)里要傳入map.entrySet()
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>()
{
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2)
{
//按照value值,重小到大排序
// return o1.getValue() - o2.getValue();
//按照value值,從大到小排序
// return o2.getValue() - o1.getValue();
//按照value值,用compareTo()方法默認(rèn)是從小到大排序
return o1.getValue().compareTo(o2.getValue());
}
});
//注意這里遍歷的是list,也就是我們將map.Entry放進(jìn)了list,排序后的集合
for (Map.Entry s : list)
{
System.out.println(s.getKey()+"--"+s.getValue());
}
}
}
輸出結(jié)果如下:沈吳--2大鳥(niǎo)--1小菜--3王二--8============排序后============大鳥(niǎo)--1沈吳--2小菜--3王二--8
有疑問(wèn),掃我二維碼添加微信,歡迎騷擾!堅(jiān)持做一件事,一起學(xué)習(xí)。
* hashMap排序
* @author lizhibiao
* @date 2018/12/3 11:47
*/
public class TestHashMapCollections
{
public static void main(String[] args)
{
Map<String, Integer> map = new HashMap<>();
map.put("王二", 8);
map.put("沈吳", 2);
map.put("小菜", 3);
map.put("大鳥(niǎo)", 1);
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
for (Map.Entry s : entrySet)
{
System.out.println(s.getKey()+"--"+s.getValue());
}
System.out.println("============排序后============");
//借助list實(shí)現(xiàn)hashMap排序//
//注意 ArrayList<>() 括號(hào)里要傳入map.entrySet()
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>()
{
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2)
{
//按照value值,重小到大排序
// return o1.getValue() - o2.getValue();
//按照value值,從大到小排序
// return o2.getValue() - o1.getValue();
//按照value值,用compareTo()方法默認(rèn)是從小到大排序
return o1.getValue().compareTo(o2.getValue());
}
});
//注意這里遍歷的是list,也就是我們將map.Entry放進(jìn)了list,排序后的集合
for (Map.Entry s : list)
{
System.out.println(s.getKey()+"--"+s.getValue());
}
}
}
輸出結(jié)果如下:沈吳--2大鳥(niǎo)--1小菜--3王二--8============排序后============大鳥(niǎo)--1沈吳--2小菜--3王二--8
有疑問(wèn),掃我二維碼添加微信,歡迎騷擾!堅(jiān)持做一件事,一起學(xué)習(xí)。
轉(zhuǎn)載于:https://www.cnblogs.com/lizb0907/p/10060349.html
總結(jié)
以上是生活随笔為你收集整理的HashMap根据value值排序的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 针对SSL/TLS的拒绝服务攻击以及使用
- 下一篇: go语言渐入佳境[9]-doublelo