Groovy web console

subscribe to the feed Subscribe
to this
site
sort and toSort in groovy (via #groovywebconsole)
tweet this snippet Tweet
this
script

sort and toSort in groovy

Published 2 months ago by Joe with tags groovy java sort toSorted dangerous #diffRuby
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
def initial = [1,3,5,4]

// sort with closure and create a new object
def sorted = initial.toSorted{ a, b -> a <=> b}

// original collection remains as initial state
println("initial after custom toSort=$initial")

// new sorted collection is as expected
println("sorted=$sorted")

// do a naughty sort
initial.sort()
// show that the initial has mutated
println("initial after dangerous sort=$initial")