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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With