java中 什么是映射,groupingby和Collectors(Java)中的映射之间有什么区别?

Take a look at this piece of code.

// group by price, uses 'mapping' to convert List to Set

Map> result =

items.stream().collect(

Collectors.groupingBy(Item::getPrice,

Collectors.mapping(Item::getName, Collectors.toSet())

)

);

Is groupingBy and Mapping interchangeable? What is their differences?

For the third parameter in collect(), would I get the same output type Map if I used Collectors.toList() instead of Collectors.toSet()? I heard that toList() is a more popular option.

解决方案

No, the two are completely different.

Collectors.groupingBy takes a function which creates keys and returns a collector which returns a map from keys to collections of objects in the stream which have that same key.

Collectors.mapping, on the other hand, takes a function and another collector, and creates a new collector which first applies the function and then collects the mapped elements using the given collectors. Thus, the following are equivalent:

items.stream().map(f).collect(c);

items.stream().collect(Collectors.mapping(f, c));

Collectors.mapping is most useful in situations where you do not have a stream, but you need to pass a collector directly. An example of such a situation is when using Collectors.groupingBy.

items.stream().collect(Collectors.groupingBy(Item::getPrice, Collectors.toSet()))

yields a Map> (assuming getPrice() returns a BigDecimal). However,

items.stream().collect(Collectors.groupingBy(Item::getPrice,

Collectors.mapping(Item::getName, Collectors.toSet())))

returns a Map>. Before collecting the items, it first applies Item.getName to them.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值