提问者:小点点

Groovy中的GroupBy


我希望按其producttype及其相应的列表>对订阅详细信息进行分组; PlanReferenceIds

键:PlanSubscription.ProductSubscription.ProductType

值:PlanSubscription.PlanReferenceID

我似乎不知道如何用“好方法”做这件事

private static Map<ProductType, List<Long>> buildPlanSubscriptionDetails(List<PlanSubscription> planSubscriptions) {
        Map<ProductType, List<Long>> subscriptionDetails = [:]

        subscriptionDetails = planSubscriptions.groupBy({it.productSubscription.productType })

        return subscriptionDetails

编辑:

这是我想出来的,但我想这不是一个很好的方法

planSubscriptions.each { PlanSubscription planSubscription ->
            List<Long> planRefIds = subscriptionDetails.get(planSubscription.productSubscription.productType)

            if (planRefIds) {
                planRefIds.add(planSubscription.planReferenceId)
            } else {
                subscriptionDetails.put(planSubscription.productSubscription.productType, [planSubscription.planReferenceId] as List)
            }
        }

提前谢谢你!


共1个答案

匿名用户

分组后应使用CollecTentries:

Map<ProductType, List<Long>> result = subscriptionDetails
        .groupBy { it.productSubscription.productType }
        .collectEntries { pt, sd ->  [pt, sd*.planReferenceId]}