如何使用groovy对列表进行分组

编程入门 行业动态 更新时间:2024-10-26 10:28:10
本文介绍了如何使用groovy对列表进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个列表,我想按照marketName和commodityName分组,列出价格:例如[Terra,Wheat,1000.0] - Terra是市场名称,Wheat是商品名称,1000.0是价格

def marketCommodityGroup = [ [Merkato,Wheat,1000.0], [Shola,Wheat,1875.0], [Merkato,Barley ,5000.0], [Merkato,小麦,1000.0], [Merkato,小麦,1500.0] ]

我希望输出为:

<$ c $ [Merkato:[Wheat:[1000.0,1000.0,1500.0]]], [Merkato:[Barley:[5000.0]]], [Shola:[Wheat:[1875.0]]] ]

解决方案

好吧,这里有一个方法。

def mapped = marketCommodityGroup.groupBy { [(it [0]):it [1]] } .collect {k,v - > def grouping = k.find {true} def prices = v.inject([]){acc,val - > acc + val [2]} [(grouping.key),[(grouping.value):prices]] } .sort {left,right - > right [0]< => left [0] } .collect { [(it [0]):it [1]] }

  • 第一个 groupBy 确实 通过市场名称和商品名称
  • collect 创建除最终 k:v association:
    • grouping 是键映射拆分中的唯一条目,因此可以重新排序到期望的形式
    • 价格用非常方便的 inject 来完成,它是Groovy等同于折叠功能语言中的操作
  • sort 用于按照指定的顺序翻转订单 - 必须确定实际的逻辑是什么,以便您可以替换它
  • last collect 做最终的地图分配以获得确切的想要的表单

是的,它有点密集和神奇的,但你总是可以移动关闭def带有适当的描述性名称。

I have a list of list that I want to group by marketName and commodityName, by listing price: e.g. ["Terra", "Wheat", 1000.0] - "Terra" is Market name, "Wheat" is Commodity Name, 1000.0 is price

def marketCommodityGroup = [ ["Merkato", "Wheat", 1000.0], ["Shola", "Wheat", 1875.0], ["Merkato", "Barley", 5000.0], ["Merkato", "Wheat", 1000.0], ["Merkato", "Wheat", 1500.0] ]

I would like the output to be:

[ ["Merkato": ["Wheat" : [1000.0, 1000.0, 1500.0]]], ["Merkato": ["Barley": [5000.0]]], ["Shola": ["Wheat": [1875.0]]] ]

解决方案

Alright, here's one way of doing it.

def mapped = marketCommodityGroup.groupBy { [(it[0]) : it[1]] }.collect { k,v -> def grouping = k.find { true } def prices = v.inject([]) { acc,val -> acc + val[2] } [ (grouping.key) , [ (grouping.value) : prices ] ] }.sort { left, right -> right[0] <=> left[0] }.collect { [(it[0]) : it[1] ] }

  • first groupBy does exactly what you said, it groups by the market name and commodity name
  • collect creates the wanted structure excluding the final k:v association:
    • grouping is the only entry in the key map split so that it can be reordered to desired form
    • prices is done with the very handy inject which is Groovy's equivalent for the fold left operation in functional languages
  • sort is for flipping the order as you specified - had to quess what the actual logic is so you may want to replace it
  • last collect does the final map assignment to get the exact wanted form

Yes, it's a bit dense and magical but you can always move the closures to defs with proper, descriptive names.

更多推荐

如何使用groovy对列表进行分组

本文发布于:2023-10-24 08:28:06,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   列表   groovy

发布评论

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

>www.elefans.com

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