Groovy web console

subscribe to the feed Subscribe
to this
site
collect_vs_each (via #groovywebconsole)
tweet this snippet Tweet
this
script

collect_vs_each

Published 3 months ago by Anonymous
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
class VLan {
    VLan(int tag) {
       this.tag = tag 
    }    
    int tag
}

def _vlan_list = [new VLan(12),new VLan(55)]

// Your way
List<String> vlan_list = new ArrayList<String>()
_vlan_list.each(){vlan->
    vlan_list.add(vlan.tag)                
}
println(vlan_list)

// The Groovy way
def vlan_list_using_collect =_vlan_list.collect() {it.tag}
println(vlan_list_using_collect)