groovy 中的并行流

问题描述 投票:0回答:1

我正在尝试在groovy中使用并行流处理两个地图。 我有两个 HashMap 类型的映射 。 地图A和地图B。我需要通过mapA 和mapB 并行流来检查MapA 的密钥是否存在于MapB 中。如果存在,则比较数组列表中的值。

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]

there will always be only two value in 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:

非常感谢任何帮助!

java groovy stream hashmap
1个回答
1
投票

我对输入映射值进行了硬编码,但下面的代码可能会达到您的预期:

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

由于并行处理,日志行的顺序在执行之间会发生变化。

© www.soinside.com 2019 - 2024. All rights reserved.