简体   繁体   English

Java流收集器在Set :: size上出现Groovy错误

[英]Java stream collectors in groovy error on Set::size

I'm trying to do a SELECT MAX(COUNT DISTINCT field_x) FROM stream GROUP BY field_y; 我正在尝试SELECT MAX(COUNT DISTINCT field_x) FROM stream GROUP BY field_y;执行SELECT MAX(COUNT DISTINCT field_x) FROM stream GROUP BY field_y; in a groovy script using Java Streams / Collectors. 在使用Java Streams / Collector的常规脚本中。 Basically, I'd like a solution for COUNT DISTINCT , that I can then feed into .max . 基本上,我想要COUNT DISTINCT的解决方案,然后将其输入.max

I've been trying the solutions from this post: java 8 - stream, map and count distinct 我一直在尝试这篇文章中的解决方案: java 8-流,映射和计数不同

But getting the error: 但是得到错误:

unexpected token: : @ line 65, column 114.
   ")}, Collectors.toSet()), Set::size).val

Groovy seems to be having a problem with Set::size and Map::size . Groovy似乎对Set::sizeMap::size

I've imported both java.util.Map and java.util.Set to no avail. 我已经导入java.util.Mapjava.util.Set都没有用。 Is this a problem with Groovy syntax / importing Java classes or a problem with how I'm using Collectors ? 这是Groovy语法/导入Java类的问题还是我使用Collectors For reference, I've merely tried to implement a forEach println on this map from the original post solution: 作为参考,我只是尝试从原始发布解决方案在此地图上实现forEach println:

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

Apologies if this is more appropriate as a comment, but SO apparently requires more reputation to comment than to ask a question. 抱歉,如果此举更适合作为评论,但很显然,SO需要更多的声誉来发表评论而不是提出问题。

Unfortunately groovy does not accepts java method reference syntax, however you can use closures and rewrite it like this 不幸的是,groovy不接受java方法引用语法,但是您可以使用闭包并像这样重写它

Map<Integer, Integer> map = bids.stream().collect(
    groupingBy(
            {bid -> bid.bidderUserId},
            collectingAndThen(
                    mapping({bid -> bid.auctionId}, toSet()),
                    {set -> set.size()})));

Or (a bit shorter) using closure with implicit parameter and method pointer operator 或者(短一点)使用带有隐式参数方法指针运算符的闭包

Map<Integer, Integer> map = bids.stream().collect(
    groupingBy(
            {it.&getBidderUserId()},
            collectingAndThen(
                    mapping({it.&getAuctionId()}, toSet()),
                    {it.&size()})));

EDIT 编辑

Or even shorter (credits to @cfrick ): 甚至更短(点数@cfrick ):

Map<Integer, Integer> map = bids.stream().collect(
    groupingBy(
            {it.bidderUserId},
            collectingAndThen(
                    mapping({it.auctionId}, toSet()),
                    {it.size()})));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM