JAVA:对HashMap按value排序

来源:互联网 发布:智能聊天机器人软件 编辑:程序博客网 时间:2024/06/04 18:32

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



0 0
原创粉丝点击