TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
如何对map进行排序呢?map内部是按照hash算法存储的,但如果能对map排序在某些时候还是有用的,如有些时候,我们希望根据 value 进行排序从而得出 key 的列表,例如下面这样一组数据
Ater
100
Yier
150
Nothing
30
Zolo
330
其中 key 是姓名,value 是积分,我们希望根据积分的多少进行排序然后获取出用户排名表。
但是 java 本身不提供这样的功能。
实现程序:
- import java.util.*;
- public class MapSort{
- public static void main(String args[]){
- HashMap datas = new HashMap(){{
- put("Ater", 100);
- put("Yier", 150);
- put("Nothing", 30);
- put("Zolo", 330);
- }};
-
- Map.Entry[] a=getSortedHashtableByValue(datas);
- for(int i=0;i< a.length;i++){
- System.out.println(a[i]);
- }
- Map.Entry[] b=getSortedHashtableByKey(datas);
-
- for(int i=0;i< b.length;i++){
- System.out.println(b[i].getKey()+"-->"+b[i].getValue());
- }
-
- }
- /**
- * @param h
- * @return
- * 实现对map按照value升序排序
- */
- @SuppressWarnings("unchecked")
- public static Map.Entry[] getSortedHashtableByValue(Map h) {
- Set set = h.entrySet();
- Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set.size()]);
- Arrays.sort(entries, new Comparator() {
- public int compare(Object arg0, Object arg1) {
- Long key1 = Long.valueOf(((Map.Entry) arg0).getValue().toString());
- Long key2 = Long.valueOf(((Map.Entry) arg1).getValue().toString());
- return key1.compareTo(key2);
- }
- });
- return entries;
- }
- /**
- * @param h
- * @return
- * 实现对map按照key排序
- */
- @SuppressWarnings("unchecked")
- public static Map.Entry[] getSortedHashtableByKey(Map h) {
- Set set = h.entrySet();
- Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set.size()]);
- Arrays.sort(entries, new Comparator() {
- public int compare(Object arg0, Object arg1) {
- Object key1 = ((Map.Entry) arg0).getKey();
- Object key2 = ((Map.Entry) arg1).getKey();
- return ((Comparable) key1).compareTo(key2);
- }
- });
- return entries;
- }
- }
复制代码 运行结果:
C: >java MapSort
Nothing=30
Ater=100
Yier=150
Zolo=330
Ater-->100
Nothing-->30
Yier-->150
Zolo-->330
源码下载:http://file.javaxxz.com/2014/10/29/235621218.zip |
|