JDK1.8對Map的最新排序方法

1.傳統排序:

//對值進行排序,此處爲降序
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueDescending(Map<K, V> map)
    {
        List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<K, V>>()
        {
            @Override
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2)
            {
                int compare = (o1.getValue()).compareTo(o2.getValue());
                return -compare;
            }
        });

        Map<K, V> result = new LinkedHashMap<K, V>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

2.新排序方法:

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean asc) 
    {
        Map<K, V> result = new LinkedHashMap<>();
        Stream<Entry<K, V>> stream = map.entrySet().stream();    
		if (asc) //升序
		{
			 //stream.sorted(Comparator.comparing(e -> e.getValue()))
			stream.sorted(Map.Entry.<K, V>comparingByValue())
				.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
		}
		else //降序
		{
			 //stream.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
			stream.sorted(Map.Entry.<K, V>comparingByValue().reversed())
				.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
		}
        return result;
    }

public static <K extends Comparable<? super K>, V > Map<K, V> sortByKey(Map<K, V> map, boolean asc) 
	{
        Map<K, V> result = new LinkedHashMap<>();
        Stream<Entry<K, V>> stream = map.entrySet().stream();
        if (asc) 
		{
        	stream.sorted(Map.Entry.<K, V>comparingByKey())
                .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        }
        else 
		{
        	stream.sorted(Map.Entry.<K, V>comparingByKey().reversed())
            	.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
		}
	    return result;
	}

3.上面的知識點補充:

jdk1.8新特性:

    a. 新增Lambda表達式和函數式接口;

    b. 新增Stream API(java.util.stream);

其他新特性見文章:https://blog.csdn.net/u014470581/article/details/54944384

 

                ---------------------------------------------歡迎關注公衆號(生活不止有代碼)-------------------------------------------------------

                                                                      

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章