Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 is now [{1=2}, {2=3}, {3=4}, {4=5}], i.e a List of Maps.

How would I be able to get a HashMap from the ArrayList using collect method? 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.

like image 805
Wizard Avatar asked Oct 28 '13 02:10

Wizard


1 Answers

You're in luck! The collectEntries method handles works just like collect but for a 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}
like image 154
doelleri Avatar answered Oct 21 '22 16:10

doelleri