java 8 - 流,地图和计数不同 [英] java 8 - stream, map and count distinct

查看:175
本文介绍了java 8 - 流,地图和计数不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次尝试使用java 8流...

My first attempt with java 8 streams...

我有一个对象Bid,表示用户对拍卖中项目的出价。我有一个出价列表,我想制作一张地图,其中包含用户出价的拍卖数量(不同)。

I have an object Bid, which represents a bid of a user for an item in an auction. i have a list of bids, and i want to make a map that counts in how many (distinct) auctions the user made a bid.

这是我对它的看法:

bids.stream()
         .collect(
             Collectors.groupingBy(
                  bid ->  Bid::getBidderUserId, 
                  mapping(Bid::getAuctionId, Collectors.toSet())
             )
         ).entrySet().stream().collect(Collectors.toMap(
             e-> e.getKey(),e -> e.getValue().size())
        );

它有效,但我觉得我在作弊,因为我流式传输地图的入口集,而不是在初始流上做一个操作...必须是一个更正确的方法来做到这一点,但我无法弄清楚...

It works, but i feel like i'm cheating, cause i stream the entry sets of the map, instead of doing a manipulation on the initial stream... must be a more correct way of doing this, but i couldn't figure it out...

谢谢

推荐答案

您可以执行 groupingBy 两次:

Map<Integer, Map<Integer, Long>> map = bids.stream().collect(
        groupingBy(Bid::getBidderUserId,
                groupingBy(Bid::getAuctionId, counting())));

这样,每个用户在每次竞价中都有多少出价。因此内部地图的大小是用户参与的拍卖数量。如果您不需要其他信息,可以这样做:

This way you have how many bids each user has in each auction. So the size of internal map is the number of auctions the user participated. If you don't need the additional information, you can do this:

Map<Integer, Integer> map = bids.stream().collect(
        groupingBy(
                Bid::getBidderUserId,
                collectingAndThen(
                        groupingBy(Bid::getAuctionId, counting()),
                        Map::size)));

这正是您所需要的:用户映射到用户参与的拍卖数量。

This is exactly what you need: mapping of users to number of auctions user participated.

更新:还有类似的解决方案,更贴近您的示例:

Update: there's also similar solution which is closer to your example:

Map<Integer, Integer> map = bids.stream().collect(
        groupingBy(
                Bid::getBidderUserId,
                collectingAndThen(
                        mapping(Bid::getAuctionId, toSet()),
                        Set::size)));

这篇关于java 8 - 流,地图和计数不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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