不灭的焱

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2019-02-18 11:00:35  修改时间:2024-03-26 05:52:50  分类:Java基础  编辑

一、简单介绍Map

在讲解Map排序之前,我们先来稍微了解下map。map是键值对的集合接口,它的实现类主要包括:HashMapHashtableTreeMap 以及 LinkedHashMap 等。其中这四者的区别如下(简单介绍):

HashMap:我们最常用的Map,它根据key的HashCode 值来存储数据,根据key可以直接获取它的Value,同时它具有很快的访问速度。HashMap最多只允许一条记录的key值为Null(多条会覆盖),允许多条记录的Value为 Null。非同步的。

Hashtable:与HashMap类似,不同的是:key和value的值均不允许为null,它支持线程的同步,即任一时刻只有一个线程能写Hashtable,因此也导致了Hashtale在写入时会比较慢。

TreeMap:能够把它保存的记录根据key排序,默认是按升序排序,也可以指定排序的比较器,当用Iterator 遍历TreeMap时,得到的记录是排过序的。TreeMap不允许key的值为null。非同步的。

LinkedHashMap:保存了记录的插入顺序,在用Iterator遍历LinkedHashMap时,先得到的记录肯定是先插入的,在遍历的时候会比HashMap慢,key和value均允许为空,非同步的。

二、Map排序

TreeMap

TreeMap默认是升序的,如果我们需要改变排序方式,则需要使用比较器:Comparator。

Comparator可以对集合对象或者数组进行排序的比较器接口,实现该接口的 public compare(T o1,To2) 方法即可实现排序,该方法主要是根据第一个参数o1,小于、等于或者大于o2分别返回负整数、0或者正整数。代码如下:

public class TreeMapTest {
    public static void main(String[] args) {
        Map<String, String> map = new TreeMap<String, String>(
                new Comparator<String>() {
                    public int compare(String obj1, String obj2) {
                        // 降序排序
                        return obj2.compareTo(obj1);
                    }
                });
        map.put("c", "ccccc");
        map.put("a", "aaaaa");
        map.put("b", "bbbbb");
        map.put("d", "ddddd");

        Set<String> keySet = map.keySet();
        Iterator<String> iter = keySet.iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            System.out.println(key + ":" + map.get(key));
        }
    }
}

输出:

d:ddddd
c:ccccc
b:bbbbb
a:aaaaa

上面例子是对根据TreeMap的key值来进行排序的,但是有时我们需要根据TreeMap的value来进行排序。对value排序我们就需要 借助于Collections的sort(List<T> list, Comparator<? super T> c)方法,该方法根据指定比较器产生的顺序对指定列表进行排序。但是有一个前提条件,那就是所有的元素都必须能够根据所提供的比较器来进行比较。如下

public class TreeMapTest {
    public static void main(String[] args) {
        Map<String, String> map = new TreeMap<String, String>();
        map.put("d", "ddddd");
        map.put("b", "bbbbb");
        map.put("a", "aaaaa");
        map.put("c", "ccccc");

        //这里将map.entrySet()转换成list
        List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(map.entrySet());
        
		//然后通过比较器来实现排序
        Collections.sort(list,new Comparator<Map.Entry<String, String>>() {
            //升序排序
            public int compare(Entry<String, String> o1,
                    Entry<String, String> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });
		
        for(Map.Entry<String,String> mapping:list){
			System.out.println(mapping.getKey() + ":" + mapping.getValue()); 
        } 
    }
}

输出:

d:ddddd
c:ccccc
b:bbbbb
a:aaaaa

HashMap

HashMap的值是没有顺序的,他是按照key的HashCode来实现的。对于这个无序的HashMap我们要怎么来实现排序呢?参照TreeMap的value排序,我们一样的也可以实现HashMap的排序。

public class HashMapTest {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("c", "ccccc");
        map.put("a", "aaaaa");
        map.put("b", "bbbbb");
        map.put("d", "ddddd");

        List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(map.entrySet());
        Collections.sort(list,new Comparator<Map.Entry<String,String>>() {
            //升序排序
            public int compare(Entry<String, String> o1,
                    Entry<String, String> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }

        });

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

输出:

d:ddddd
c:ccccc
b:bbbbb
a:aaaaa

三、Map排序 助手类 (按键名/键值 升序/降序 排序)

package wen.jianbao.helper;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Map助手类
 */
public class MapHelper {
    private static int ORDER_BY_KEY   = 1;  // 按键名排序
    private static int ORDER_BY_VALUE = 2;  // 按值排序
    public static  int ORDER_NUMERIC  = 1;  // 把每一项作为数字来处理
    public static  int ORDER_STRING   = 2;  // 把每一项作为字符串来处理

    /**
     * 按键值 升序排列
     */
    public static Map<String, Object> asort(Map<String, Object> map, int... orderValueType) {
        return _sort(map, ORDER_BY_VALUE, "ASC", orderValueType);
    }

    /**
     * 按键值 降序排列
     */
    public static Map<String, Object> arsort(Map<String, Object> map, int... orderValueType) {
        return _sort(map, ORDER_BY_VALUE, "DESC", orderValueType);
    }

    /**
     * 按键名 升序排序
     */
    public static Map<String, Object> ksort(Map<String, Object> map, int... orderValueType) {
        return _sort(map, ORDER_BY_KEY, "ASC", orderValueType);
    }

    /**
     * 按键名 降序排序
     */
    public static Map<String, Object> krsort(Map<String, Object> map, int... orderValueType) {
        return _sort(map, ORDER_BY_KEY, "DESC", orderValueType);
    }

    /**
     * [一维] 排序
     *
     * @param map            排序对象
     * @param orderBy        排序类型,1:按键名,2:按键值 排序
     * @param orderType      排序方式,ASC:升序,DESC:降序
     * @param orderValueType 排序值类型,1:数字类型,2:字符串类型
     * @return 排序结果
     */
    private static Map<String, Object> _sort(Map<String, Object> map, int orderBy, String orderType, int... orderValueType) {
        int                             _orderValueType = orderValueType.length > 0 ? orderValueType[0] : ORDER_STRING;
        Map<String, Object>             sortedMap       = new LinkedHashMap<>();
        List<Map.Entry<String, Object>> entryList       = new ArrayList<>(map.entrySet());

        String _orderType = orderType.toUpperCase();
        Collections.sort(entryList, new Comparator<Map.Entry<String, Object>>() {
            @Override
            public int compare(Map.Entry<String, Object> entry1, Map.Entry<String, Object> entry2) {
                if (_orderValueType == ORDER_NUMERIC) {
                    if (_orderType.equals("ASC")) {   // 升序
                        return _getInt(
                            orderBy == ORDER_BY_KEY ? entry1.getKey() : entry1.getValue().toString()
                        ).compareTo(_getInt(
                            orderBy == ORDER_BY_KEY ? entry2.getKey() : entry2.getValue().toString()
                        ));
                    } else {                        // 降序
                        return _getInt(
                            orderBy == ORDER_BY_KEY ? entry2.getKey() : entry2.getValue().toString()
                        ).compareTo(_getInt(
                            orderBy == ORDER_BY_KEY ? entry1.getKey() : entry1.getValue().toString()
                        ));
                    }
                } else {
                    if (_orderType.equals("ASC")) {   // 升序
                        return (
                            orderBy == ORDER_BY_KEY ? entry1.getKey() : entry1.getValue().toString()
                        ).compareTo(
                            orderBy == ORDER_BY_KEY ? entry2.getKey() : entry2.getValue().toString()
                        );
                    } else {                        // 降序
                        return (
                            orderBy == ORDER_BY_KEY ? entry2.getKey() : entry2.getValue().toString()
                        ).compareTo(
                            orderBy == ORDER_BY_KEY ? entry1.getKey() : entry1.getValue().toString()
                        );
                    }
                }
            }
        });

        for (Map.Entry<String, Object> entry : entryList) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }
    
    private static Integer _getInt(Object str) {
		int i = 0;
		try {
			Pattern p = Pattern.compile("^\\d+");
			Matcher m = p.matcher(str.toString());
			if (m.find()) {
				i = Integer.valueOf(m.group());
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		
		return i;
	}
}

使用举例:

Map<String, Object> map = new HashMap<>();
map.put("d", "9");
map.put("b", "11");
map.put("a", "7");
map.put("c", "123");

Map<String,Object> map2 = MapHelper.arsort(map, MapHelper.ORDER_NUMERIC);

for (Map.Entry<String, Object> mapping : map2.entrySet()) {
	System.out.println(mapping.getKey() + ":" + mapping.getValue());
}

输出:

c:123
b:11
d:9
a:7