Groovy中的过滤Map键长度

ehxuflar  于 2023-03-01  发布在  其他
关注(0)|答案(2)|浏览(201)

我正在尝试创建一个新的Map,从另一个Map中提取键,并尝试插入长度小于13个字符的键。我尝试过这样过滤,但这对我来说是不可能的。

Map<String, String> maps = entriesOnlyOnLeft.findAll { it.key }.each { it.key.length() < 13 }

输出:

log.info("Key Map ---> "+maps.keySet())
[431486899900600, 280799200020001, 251206899900600, 080196899900604, 350166899900600, 180876899900600, 260896899900600, 372746899900600, 442166899900600, 330446899900600, 401946899900600, 110126899900600, 200696899900600, 410916899900600, 060156899900600, 210416899900600, 040136899900600, 290676899900600, 140216899900600, 020036899900600, 360386899900600, 312016899900600, 280796800220073, 451686899900600, 150306899900600, 280796800110071, 280796899900604, 320546899900600, 492756899900600, 240896899900600, 380386899900600, 000000E04921301, 100376899900600, 480206899900600, 000000E00004101, 280796800330051, 280796800330064, 050196899900600, 170796899900600, 390756899900600, 520016899900600, 000000E04921701, 280796899900075, 280796899900074, 280796899900077, 280796899900076, 280796899900079, 280796899900078, 280796899900065, 280796899900053, 280796899900057, 280796899900040, 280796899900041, 280796899900046, 280796899900045, 280796899900048, 280796899900049, 191306899900600, 030146899900600, 280796899900032, 280796899900035, 280796899900034, 280796899900036, 280796899900039, 280796899900038, 280796800440072, 341206899900600, 160786899900600, 130346899900600, 120406899900600, 510016899900600, 502976899900600, 471866899900600, 270286899900600, 300306899900600, 090596899900600, 000000E04924801, 230506899900600, 462506899900600, 070406899900600]
jucafojl

jucafojl1#

你差点就成功了。解决办法是:

Map<String,String> results = entriesOnlyOnLeft.findAll { it.key.length() < 13 }

findAll中使用的闭包必须返回真实的结果,才能在结果中包含该Map.Entry。此外,还将为给定Map中的每个项目调用findAll闭包(即entriesOnlyOnLeft),因此不需要调用each。加上each返回void,因此不会出现“t是通过调用each返回给调用者的任何结果。

5us2dqdw

5us2dqdw2#

你可以试试下面的方法(有点变异的方法)

Map<String, String> maps = new HashMap<>();    
entriesOnlyOnLeft.each { it ->     
    if (it.key.length() < 13) {
        maps.put(it.key, it.value)
    } 
}

相关问题