java8 treemap 排序_Java8中对HashMap的Value值进行排序

在Java8中对java.util.Comparator 和 Map.Entry 增加了新的方法用来排序。可以对HashMap, HashSet, HashTable, LinkedHashMap, TreeMap, 甚至ConcurrentHashMap都可以排序。基本思路就是先拿到集合,可以用entrySet()方法得到。然后调用stream方法,里面就可以调用sort方法了。对Map的排序,一般涉及两种,一是针对key,另外一种是针对value进行排序.对key的排序比较简单,这里主要介绍对Value的排序。

1. 对Value进行排序package com.java8.maptest;

import java.util.Collections;

import java.util.Comparator;

import java.util.HashMap;

import java.util.LinkedHashMap;

import java.util.Map;

import static java.util.stream.Collectors.*;

import static java.util.Map.Entry.*;

/*

* Java Program to sort a Map by values in Java 8

*

*/

public class MapSortByValue {

public static void main(String[] args) throws Exception {

// a Map with string keys and integer values

Mapbudget = new HashMap<>();

budget.put("clothes", 120);

budget.put("grocery", 150);

budget.put("transportation", 100);

budget.put("utility", 130);

budget.put("rent", 1150);

budget.put("miscellneous", 90);

System.out.println("map before sorting: " + budget);

// let's sort this map by values first

Mapsorted = budget

.entrySet()

.stream()

.sorted(comparingByValue())

.collect(

toMap(e -> e.getKey(), e -> e.getValue(), (e1, e2) -> e2,

LinkedHashMap::new));

System.out.println("map after sorting by values: " + sorted);

// above code can be cleaned a bit by using method reference

sorted = budget

.entrySet()

.stream()

.sorted(comparingByValue())

.collect(

toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,

LinkedHashMap::new));

// now let's sort the map in decreasing order of value

sorted = budget

.entrySet()

.stream()

.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))

.collect(

toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,

LinkedHashMap::new));

System.out.println("map after sorting by values in descending order: "

+ sorted);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值