流分组方式:减少到列表的第一个元素

编程入门 行业动态 更新时间:2024-10-14 08:22:54
本文介绍了流分组方式:减少到列表的第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个List<Valuta>,可以表示(简化)JSON样式:

I have a List<Valuta> which can be represented (simplified) JSON-style:

[{codice = EUR,描述=欧元,比率= 1},{codice = USD, description =美元,比率= 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,描述=欧元,比率= 1},USD = {codice = USD, description =美元,比率= 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<Valuta>>而不是我所需要的.

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.

更多推荐

流分组方式:减少到列表的第一个元素

本文发布于:2023-11-25 10:39:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1629427.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:第一个   元素   方式   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!