Stream groupingBy: reducing to first element of list(Stream groupingBy:减少到列表的第一个元素)
问题描述
我有一个 List<Valuta> 可以表示(简化)JSON 样式:
I have a List<Valuta> which can be represented (simplified) JSON-style:
[ { 代码=欧元,描述=欧元,比率=1 },{ 代码=美元,描述=美元,比率=1.1 } ]
[ { codice=EUR, description=Euro, ratio=1 }, { codice=USD, description=Dollars, ratio=1.1 } ]
我想像这样在 Map<String, Valuta> 中转换它:
I want to transform that in a Map<String, Valuta> like this:
{ EUR={ codice=EUR, description=Euro, ratio=1 }, USD={ codice=USD,描述=美元,比率=1.1 }}
{ EUR={ codice=EUR, description=Euro, ratio=1 }, USD={ codice=USD, description=Dollars, ratio=1.1 }}
我写了这个单行:
getValute().stream().collect(Collectors.groupingBy(Valuta::getCodice));
但这会返回一个 Map<String, List
but this returns a Map<String, List<Valuta>> instead of what I need.
我想 mapping() 函数对我有用,但不知道如何.
I suppose mapping() function would work for me, but don't know how.
推荐答案
其实这里需要使用Collectors.toMap,而不是Collectors.groupingBy:
Actually, you need to use Collectors.toMap here instead of Collectors.groupingBy:
Map<String, Valuta> map =
getValute().stream()
.collect(Collectors.toMap(Valuta::getCodice, Function.identity()));
groupingBy 用于根据分组函数对 Stream 的元素进行分组.2 与分组功能结果相同的Stream元素,默认会被收集到一个List中.
toMap 会将元素收集到 Map 中,其中键是应用给定键映射器的结果,并且该值是应用值映射器的结果.注意toMap,默认情况下,如果遇到重复,会抛出异常.
toMap will collect the elements into a Map where the key is the result of applying a given key mapper and the value is the result of applying a value mapper. Note that toMap, by default, will throw an exception if a duplicate is encountered.
这篇关于Stream groupingBy:减少到列表的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Stream groupingBy:减少到列表的第一个元素
基础教程推荐
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
