在java中按值排序地图 [英] Sort Map by value in java

查看:135
本文介绍了在java中按值排序地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是给出一个返回升序数组/排序键值列表的地图。例如:

My goal is to have is given a map of to return an ascending array/list of sorted key values. For example:

输入:包含以空格分隔的以下键/值条目的地图:

Input: the Map containing the following key/value entries separated by a space:

"Apple" 10
"Orange" 8
"Kiwi" 15

输出:

{Orange;Apple;Kiwi}

我想到的唯一其他方法是创建一个 Map< Integer,Set< String>> 然后按照相当复杂的键进行排序。我有这种方法工作,但在代码和逻辑方面似乎效率低下。非常感谢!

The only other approach I could think of was creating a Map<Integer,Set<String>> and then sorting by the key which is fairly convoluted. I got this approach to work but it seems rather inefficient in terms of code and logic. Thanks so much!

推荐答案

java 8 中有一个非常简单的方法来使用流:

In java 8 there is a very simple approach to this using streams:

map.entrySet().stream()
    .sorted(Map.Entry.comparingByValue())
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

例如:

public class Test {
    public static void main(String[] args) {
        Map<String, Integer> map = new TreeMap<>();
        map.put("A", 2);
        map.put("B", 3);
        map.put("C", 1);
        System.out.println(map.entrySet().stream()
            .sorted(Map.Entry.comparingByValue())
            .map(Map.Entry::getKey)
            .collect(Collectors.toList()));
    }
}

打印[C,A,B]

这篇关于在java中按值排序地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆