Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Groovy:根据字段值从列表中获取子列表_Groovy - Fatal编程技术网

Groovy:根据字段值从列表中获取子列表

Groovy:根据字段值从列表中获取子列表,groovy,Groovy,如何根据用户对象的类型对其进行分组。例如,我有如下列表 List userList = [userA, userB, userC, userD, userE, userF, userH] 我想把这个列表转换成一个列表 List userList = [ [userA, userB], [userC, userD, userE, userF], [userH] ] 根据用户的类型字段进行分组。groovy的优点,并且只一行代码:-) groovy的优点,而且只有一行代码 您可以使用group

如何根据用户对象的类型对其进行分组。例如,我有如下列表

List userList = [userA, userB, userC, userD, userE, userF, userH]
我想把这个列表转换成一个列表

List userList = [ [userA, userB], [userC, userD, userE, userF], [userH] ] 

根据用户的类型字段进行分组。

groovy的优点,并且只一行代码:-)


groovy的优点,而且只有一行代码


您可以使用
groupyBy()
方法:

Map map = users.groupBy { it.type }
这将返回按类型分组的用户对象的映射。 地图内容如下所示:

[
  typeA : [list of users of typeA], 
  typeB : [list of users of typeB], 
  ..
]
[ [list of users of typeA], [list of users of typeB], .. ]
可以使用collect方法轻松地将此映射转换为所需的列表:

List l = m.collect { key, value -> value }
现在,
l
是一个如下所示的列表:

[
  typeA : [list of users of typeA], 
  typeB : [list of users of typeB], 
  ..
]
[ [list of users of typeA], [list of users of typeB], .. ]
一网打尽:

def list = users.groupBy { it.type } .collect { k, v -> v }

您可以使用
groupyBy()
方法:

Map map = users.groupBy { it.type }
这将返回按类型分组的用户对象的映射。 地图内容如下所示:

[
  typeA : [list of users of typeA], 
  typeB : [list of users of typeB], 
  ..
]
[ [list of users of typeA], [list of users of typeB], .. ]
可以使用collect方法轻松地将此映射转换为所需的列表:

List l = m.collect { key, value -> value }
现在,
l
是一个如下所示的列表:

[
  typeA : [list of users of typeA], 
  typeB : [list of users of typeB], 
  ..
]
[ [list of users of typeA], [list of users of typeB], .. ]
一网打尽:

def list = users.groupBy { it.type } .collect { k, v -> v }

从给定的列表创建一个映射,其中键为类型,值为用户列表。最后调用map.toList方法。从给定列表创建一个映射,其中键为类型,值为用户列表。最后调用map.toList方法。您还可以在groupBy结果上使用spread,而不是collect
用户。groupBy{it.value}*.value
您还可以在groupBy结果上使用spread,而不是collect
用户。groupBy{it.value}*.value