我正在尝试在 Groovy 中使用并行流处理两个地图。
我有两张类型为
HashMap<Object, ArrayList>
、mapA
和 mapB
的地图。我需要通过 mapA
与 mapB
并行流来检查 mapA
的密钥是否存在于 mapB
中。如果该值存在,则比较 ArrayList
内的值。
def Map = [:].withDefault {key -> return []}
//populating two maps
def jsonSlurper = new JsonSlurper()
while ((inputLine = reader.readLine()) != null) {
if (inputLine.startsWith('{"k"')) {
def json =jsonSlurper.parseText(inputLine)
Map.put(json.key[3],
[json.key[4],json.key[5]])
}
}
// comparing to map to check if key exists, if yes then compare value[0] of mapA to mapB's Value[0].. and then value[1] and so on.
def compareDatastore = { mapA,mapB ->
mapA.entrySet().parallelStream().with {
**it.forEach(entry->{**
if(mapB.containsKey(entry.getKey())){
if(entry.getValue().get(0)!=mapB.get(entry.getKey()).get(0) || entry.getValue().get(1)!=mapB.get(entry.getKey()).get(1))
println "noMatch"
}else{
println "notFound"
}
})
}
}
我怎样才能做得更好?
地图中的示例值为:
key=1245,value=[a,b]
key=1234,value=[b,a]
每个
ArrayList
中始终只有两个值。
我在上面代码中的
forEach
行收到以下错误。
Caught: java.lang.VerifyError: Bad local variable type
Exception Details:
Location:
scripts/smething$_run_closure6$_closure8$_closure9.doCall(Ljava/lang/Object;)Ljava/lang/Object; @155: aload_3
Reason:
Type top (current frame, locals[3]) is not assignable to reference type
Current Frame:
我对输入映射值进行了硬编码,但下面的代码可能会达到您的预期:
def mapA = [
'key1': ['1', '2'],
'key2': ['3', '4'],
'key4': ['5', '6']
]
def mapB = [
'key1': ['1', '2'],
'key3': ['3', '4'],
'key4': ['5', '7']
]
mapA.entrySet().parallelStream().forEach { entry ->
if (mapB.containsKey(entry.key)) {
if (entry.value != mapB[entry.key]) {
println "'${entry.key}' key doesn't have matching value"
} else {
println "'${entry.key}' key has matching value"
}
} else {
println "'${entry.key}' key not found"
}
}
执行时,它会打印以下几行:
'key2' key not found
'key4' key doesn't have matching value
'key1' key has matching value
由于并行处理,日志行的顺序在执行之间会发生变化。