我有Map [name:name1,type:type1,desc:desc1,ordinal:1]的流。如何转换/分组(使用Groovy)到Map>:Map(类型1:地图(neme:name1,desc:desc1,ordinal:1))。 地图流
[name:productName, type:IN, ordinal:1, description:desc]
[name:productName1, type:IN, ordinal:2, description:desc]
[name:productName2, type:OUT, ordinal:3, description:desc]
我得到了:地图:
IN: Map[
[name:productName, type:IN, ordinal:1, description:desc.],
[name:productName1, type:IN, ordinal:2, description:desc.]]
OUT: Map[
[name:productName2, type:OUT, ordinal:3, description:desc.]]
答案 0 :(得分:0)
您可以将Stream.collect()
方法与Collectors.groupingBy { it.type }
一起使用,以收集所有元素,作为type
键的映射和元素列表的值。考虑以下示例:
import java.util.stream.Collectors
import java.util.stream.Stream
def input = Stream.of(
[name: 'productName', type: 'IN', ordinal: 1, description: 'desc'],
[name: 'productName1', type: 'IN', ordinal: 2, description: 'desc'],
[name: 'productName2', type: 'OUT', ordinal: 3, description: 'desc'],
)
def result = input.collect(Collectors.groupingBy { it.type })
result.each { println it }
输出:
IN=[{name=productName, type=IN, ordinal=1, description=desc}, {name=productName1, type=IN, ordinal=2, description=desc}]
OUT=[{name=productName2, type=OUT, ordinal=3, description=desc}]
或者,如果您输入的不是Stream
而是List
,则可以使用效果良好的老式Groovy Collection.groupBy()
:
def input2 = [[name: 'productName', type: 'IN', ordinal: 1, description: 'desc'],
[name: 'productName1', type: 'IN', ordinal: 2, description: 'desc'],
[name: 'productName2', type: 'OUT', ordinal: 3, description: 'desc']]
def result2 = input2.groupBy { it.type }
result2.each { println it }