简体   繁体   English

使用collect闭包方法在groovy中填充HashMap

[英]Using collect closure method to populate a HashMap in groovy

I am trying to populate a Map from an List. 我试图从列表填充地图。 Here's what I am doing. 这就是我在做什么。

itemNoList = [1,2,3,4]
bookMap = [:]
bookMap = itemNoList.collect{ [ (it) : it+1 ] }

When I do this, the bookMap changes to ArrayList type and now has a List of HashMap. 当我这样做时,bookMap变为ArrayList类型,现在有一个HashMap列表。

bookMap is now [{1=2}, {2=3}, {3=4}, {4=5}] , ie a List of Maps. bookMap现在是[{1=2}, {2=3}, {3=4}, {4=5}] ,即地图列表。

How would I be able to get a HashMap from the ArrayList using collect method? 我怎样才能使用collect方法从ArrayList获取HashMap? It would be easy to solve this by using an each instead collect , but I'm just curious whether it could be solved using collect . 通过使用each而不是collect来解决这个问题很容易,但我只是好奇它是否可以使用collect来解决。

You're in luck! 你很幸运! The collectEntries method handles works just like collect but for a Map! collectEntries方法处理工作就像collect但是对于Map!

groovy:000> itemNoList = [1, 2, 3, 4]
===> [1, 2, 3, 4]
groovy:000> itemNoList.collectEntries { [(it): it+1] }
===> {1=2, 2=3, 3=4, 4=5}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM