java8新特性:對map集合排序

1、簡單介紹Map

在講解Map排序以前,咱們先來稍微瞭解下map,map是鍵值對的集合接口,它的實現類主要包括:HashMap, TreeMap, Hashtable以及LinkedHashMap等。其中這四者的區別以下(簡單介紹):java

HashMap:咱們最經常使用的Map,HashMap是無序的,它根據key的HashCode 值來存儲數據,根據key能夠直接獲取它的Value,同時它具備很快的訪問速度。HashMap最多隻容許一條記錄的key值爲Null(多條會覆蓋);容許多條記錄的Value爲 Null。非同步的。數組

TreeMap:可以把它保存的記錄根據key排序,默認是按升序排序,也能夠指定排序的比較器,當用Iterator 遍歷TreeMap時,獲得的記錄是排過序的。TreeMap不容許key的值爲null。非同步的。app

Hashtable:與HashMap相似,不一樣的是:key和value的值均不容許爲null;它支持線程的同步,即任一時刻只有一個線程能寫Hashtable, 所以也致使了Hashtale在寫入時會比較慢。google

LinkedHashMap:LinkedHashMap是有序的,保存了記錄的插入順序,在用Iterator遍歷LinkedHashMap時,先獲得的記錄確定是先插入的.在遍歷的時候會比HashMap慢。key和value均容許爲空,非同步的。spa

2、Map排序

java8新特性:對map集合排序,根據key或者value操做排序(升序、降序)線程

package com.drew.test;

import java.util.List;
import java.util.Map;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * @author zero 2019/04/08
 */
public class Java8future {

    public static void main(String[] args) {
        Map<String, Integer> map = ImmutableMap.of("0", 3, "1", 8, "0.29", 7, "1.67", 3);
        System.out.println("原始的map:" + map);
        System.out.println("根據map的key降序:" + sortByKey(map, true));
        System.out.println("根據map的key升序:" + sortByKey(map, false));
        System.out.println("根據map的value降序:" + sortByValue(map, true));
        System.out.println("根據map的value升序:" + sortByValue(map, false));
    }

    /**
     * 根據map的key排序
     * 
     * @param map 待排序的map
     * @param isDesc 是否降序,true:降序,false:升序
     * @return 排序好的map
     * @author zero 2019/04/08
     */
    public static <K extends Comparable<? super K>, V> Map<K, V> sortByKey(Map<K, V> map, boolean isDesc) {
        Map<K, V> result = Maps.newLinkedHashMap();
        if (isDesc) {
            map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey().reversed())
                .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        } else {
            map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey())
                .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        }
        return result;
    }

    /**
     * 根據map的value排序
     * 
     * @param map 待排序的map
     * @param isDesc 是否降序,true:降序,false:升序
     * @return 排序好的map
     * @author zero 2019/04/08
     */
    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean isDesc) {
        Map<K, V> result = Maps.newLinkedHashMap();
        if (isDesc) {            
            map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByValue().reversed())
            .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        } else {            
            map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByValue())
            .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        }
        return result;
    }
}

HashMap

咱們知道HashMap的值是沒有順序的,他是按照key的HashCode來實現的。對於這個無序的HashMap咱們要怎麼來實現排序呢?參照TreeMap的value排序,咱們同樣的也能夠實現HashMap的排序。code

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");

//這裏將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

TreeMap

TreeMap默認是升序的,若是咱們須要改變排序方式,則須要使用比較器:Comparator對象

Comparator能夠對集合對象或者數組進行排序的比較器接口,實現該接口的public compare(T o1,To2)方法便可實現排序,該方法主要是根據第一個參數o1小於、等於或者大於o2分別返回負整數、0或者正整數。代碼以下:blog

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

 

相關文章
相關標籤/搜索