鉴于我的Widget
课程:
class Widget {
String name
WidgetType type
boolean isRad
}
enum WidgetType {
Fizz, Buzz, Foo
}
我的常规代码将被List<Widget>
传递,可能将被填充如下:
List<Widget> allWidgets = []
Widget w1 = new Widget(name: "W1", type: WidgetType.Fizz, isRad: true)
Widget w2 = new Widget(name: "W2", type: WidgetType.Fizz, isRad: true)
Widget w3 = new Widget(name: "W3", type: WidgetType.Buzz, isRad: false)
Widget w4 = new Widget(name: "W4", type: WidgetType.Buzz, isRad: false)
Widget w5 = new Widget(name: "W5", type: WidgetType.Foo, isRad: true)
Widget w6 = new Widget(name: "W6", type: WidgetType.Foo, isRad: false)
allWidgets << w1
allWidgets << w2
allWidgets << w3
allWidgets << w4
allWidgets << w5
allWidgets << w6
我想要完成的是根据allWidgets
对Widget#type
中所有元素进行分组。如此有效,将上面的列表转换为多个列表(每个type
1个),如下所示:
List<Widget> fizzWidgets = []
List<Widget> buzzWidgets = []
List<Widget> gooWidgets = []
Widget w1 = new Widget(name: "W1", type: WidgetType.Fizz, isRad: true)
Widget w2 = new Widget(name: "W2", type: WidgetType.Fizz, isRad: true)
Widget w3 = new Widget(name: "W3", type: WidgetType.Buzz, isRad: false)
Widget w4 = new Widget(name: "W4", type: WidgetType.Buzz, isRad: false)
Widget w5 = new Widget(name: "W5", type: WidgetType.Foo, isRad: true)
Widget w6 = new Widget(name: "W6", type: WidgetType.Foo, isRad: false)
fizzWidgets << w1
fizzWidgets << w2
buzzWidgets << w3
buzzWidgets << w4
fooWidgets << w5
fooWidgets << w6
我相信可以在这里使用collect
关闭,但到目前为止我的所有尝试都失败了,我最好的是:
allWidgets.collect { widget ->
it.type
}
我能在这做什么?虽然我接受一个纯粹的Java答案,但我真的希望有一些非常优雅的东西......好吧,很时髦。
答案 0 :(得分:4)
您需要的不是collect
而是groupBy
:
allWidgets.groupBy { it.type }
结果将返回Map<WidgetType, List<Widget>>
。
演示:
enum WidgetType {
Fizz, Buzz, Foo
}
class Widget {
String name
WidgetType type
boolean isRad
}
List<Widget> allWidgets = [
Widget w1 = new Widget(name: "W1", type: WidgetType.Fizz, isRad: true),
Widget w2 = new Widget(name: "W2", type: WidgetType.Fizz, isRad: true),
Widget w3 = new Widget(name: "W3", type: WidgetType.Buzz, isRad: false),
Widget w4 = new Widget(name: "W4", type: WidgetType.Buzz, isRad: false),
Widget w5 = new Widget(name: "W5", type: WidgetType.Foo, isRad: true),
Widget w6 = new Widget(name: "W6", type: WidgetType.Foo, isRad: false),
]
def grouped = allWidgets.groupBy { it.type }
List<Widget> fizzWidgets = grouped[WidgetType.Fizz]
List<Widget> buzzWidgets = grouped[WidgetType.Buzz]
List<Widget> fooWidgets = grouped[WidgetType.Foo]
assert fizzWidgets.size() == 2
assert fizzWidgets.every { it.type == WidgetType.Fizz }
assert buzzWidgets.size() == 2
assert buzzWidgets.every{ it.type == WidgetType.Buzz }
assert fooWidgets.size() == 2
assert fooWidgets.every { it.type == WidgetType.Foo }
assert grouped instanceof Map
assert grouped.keySet().every { it instanceof WidgetType }
assert grouped.values().every { it instanceof List }
assert grouped.values().flatten().every { it instanceof Widget }
Here您可以找到groupBy
个文档。