Java 8 流映射到按值排序的键列表 [英] Java 8 stream map to list of keys sorted by values

查看:28
本文介绍了Java 8 流映射到按值排序的键列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有地图 MapcountByType 并且我想要一个列表,该列表按相应的值对键进行了排序(最小到最大).我的尝试是:

I have map Map<Type, Long> countByType and I want to have a list which has sorted (min to max) keys by their corresponding values. My try is:

countByType.entrySet().stream().sorted().collect(Collectors.toList());

然而,这只是给了我一个条目列表,我怎样才能在不丢失顺序的情况下获得类型列表?

however this just gives me a list of entries, how can I get a list of types, without losing the order?

推荐答案

你说你想按值排序,但你的代码中没有.将 lambda(或方法引用)传递给 sorted 以告诉它您想要如何排序.

You say you want to sort by value, but you don't have that in your code. Pass a lambda (or method reference) to sorted to tell it how you want to sort.

而你想拿到钥匙;使用 map 将条目转换为键.

And you want to get the keys; use map to transform entries to keys.

List<Type> types = countByType.entrySet().stream()
        .sorted(Comparator.comparing(Map.Entry::getValue))
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());

这篇关于Java 8 流映射到按值排序的键列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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