我了解Java但对Groovy来说却是全新的。我在Groovy中有一些遗留代码可供使用。
我在Groovy中有以下方法:
def mapMyNotificationsByFruits(prefs,fruits) {
def map = [:]
prefs.each { MainNotification cn ->
cn.fruits.each {
MyNotification an ->
def ex = map[(an.fruitId)]
if (!ex) ex = []
ex.add(an)
map[(an.fruitId)] = ex
}
}
log.info("map is: $map")
return map
}
上面的方法从另一个方法调用如下:
def notificationPrefsByFruit = mapMyNotificationsByFruits(prefs, fruits)
当我在mapMyNotificationsByFruits
方法的第一行调试时,我得到prefs
为
MainNotification [someId=ABC123, email=abc@gmail.com, fruits=[{fruitId=XYZ123, someField=0}]]
运行此代码时,出现以下错误:
groovy.lang.MissingMethodException: No signature of method: com.somepackage.SomeClass$_mapMyNotificationsByFruits_closure5$_closure10.doCall() is applicable for argument types: (groovy.json.internal.LazyMap) values: [[{fruitId=XYZ123, someField=0}]]
这里有什么问题?
这些行做了什么:
MyNotification an ->
def ex = map[(an.fruitId)]
if (!ex) ex = []
ex.add(an)
map[(an.fruitId)] = ex
是铸造问题吗?
使用以下代码替换上述行可解决此问题:
MyNotification an = it
def ex = map[(an.fruitId)]
if (!ex) ex = []
ex.add(an)
map[(an.fruitId)] = ex
但我不确定两个代码块是否相同,我正在修复它。
提前致谢!
答案 0 :(得分:0)
算法做了什么?
鉴于MainNotification
个实例列表,它按MyNotification
对fruitId
个实例进行分组。
鉴于:
[
[
someId: "ABC123",
email: "abc@gmail.com",
fruits: [
[fruitId : "XYZ123", someField: 0],
[fruitId : "XYZ124", someField: 6],
]
],
[
someId: "XYSK",
email: "yax@gmail.com",
fruits: [
[fruitId : "XYZ123", someField: 5],
[fruitId : "XYZ124", someField: 2],
[fruitId : "XYZ144", someField: 9],
]
]
]
预期输出:
[
XYZ123 : [
[fruitId : "XYZ123", someField: 0],
[fruitId : "XYZ123", someField: 5]
],
XYZ124 : [
[fruitId : "XYZ124", someField: 6],
[fruitId : "XYZ124", someField: 2]
],
XYZ144 : [
[fruitId : "XYZ144", someField: 9]
]
]
更正:
List<MainNotification>
而不是。{
MainNotification
。MyNotification
的实例(这是你的主要修复
问题btw )。您没有发布MainNotification
和MyNotification
的源代码,因此根据您在问题中提供的输入数据,我将其模仿为:
class MainNotification{
String someId;
String email;
List<MyNotification> fruits;
}
class MyNotification{
String fruitId;
int someField;
}
这里的更正和假设是工作代码:
def mapMyNotificationsByFruits(prefs,fruits) {
def map = [:]
prefs.each { MainNotification cn ->
cn.fruits.each { MyNotification an ->
def ex = map[(an.fruitId)]
if (!ex) ex = []
ex.add(an)
map[(an.fruitId)] = ex
}
}
println ("map is: $map")
return map
}
MainNotification mainNotification = new MainNotification(someId: "ABC123",
email: "abc@gmail.com",
fruits: [new MyNotification(fruitId : "XYZ123", someField: 0)]
);
MyNotification fruits = null; //never used on the method
List<MainNotification> prefs = [mainNotification];
def notificationPrefsByFruit = mapMyNotificationsByFruits(prefs, fruits)