JAVA:对HashMap按value排序

TreeMap对key排序,下面我们实现Map对value排序:

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

/**
 * Created by fhqplzj on 16-6-27.
 */
public class SortedByValue {
    private static final String keyData = "said:that:with:from:have:were:they:will:would:about:year:this:been:their:percent:which:after:more:people:also";
    private static final String valueData = "12856:8859:5422:4544:3600:3563:2980:2619:2567:2360:2286:2185:2182:2068:1950:1937:1927:1766:1731:1625";

    public static void fillMap(Map<String, Integer> map) {
        List<String> keys = Arrays.stream(keyData.split(":")).collect(Collectors.toList());
        List<Integer> values = Arrays.stream(valueData.split(":")).map(Integer::new).collect(Collectors.toList());
        Collections.shuffle(keys);
        Collections.shuffle(values);
        keys.forEach(key -> map.put(key, values.get(keys.indexOf(key))));
        map.entrySet().forEach(System.out::println);
    }

    public static void main(String[] args) {
        //填充map,map的values是乱序的
        Map<String, Integer> map = new HashMap<>();
        fillMap(map);
        //第一步:将map转化为list
        List<Map.Entry<String, Integer>> list = map.entrySet().stream().sorted(((o1, o2) -> o2.getValue().compareTo(o1.getValue()))).collect(Collectors.toList());
        //第二步:将list转化为LinkedHashMap
        Map<String, Integer> result = new LinkedHashMap<>();
        list.forEach(stringIntegerEntry -> result.put(stringIntegerEntry.getKey(), stringIntegerEntry.getValue()));
        //第三步:打印结果看看
        char[] chars = new char[50];
        Arrays.fill(chars, '*');
        System.out.println(String.valueOf(chars) + "分割线" + String.valueOf(chars));
        result.entrySet().forEach(System.out::println);
    }
}
实验结果为:

which=2980
been=5422
will=2360
year=2619
more=8859
this=1766
about=4544
their=1937
also=1927
percent=2185
people=3563
that=1625
with=1950
would=12856
were=2182
have=2286
from=2567
after=2068
said=1731
they=3600
**************************************************分割线**************************************************
would=12856
more=8859
been=5422
about=4544
they=3600
people=3563
which=2980
year=2619
from=2567
will=2360
have=2286
percent=2185
were=2182
after=2068
with=1950
their=1937
also=1927
this=1766
said=1731
that=1625



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值