I have an array in Scala with the class ArrayBuffer[Actor], where Actor is a class that implements the Ordered[Actor] trait. How do I sort this array without coding it manually?
I know there is an object called Sorting, but it doesnt seem to work since ArrayBuffer doesn’t implement/extend the right classes.
How do I sort ArrayBuffer[A] type arrays?
If you are using Scala 2.8, you could use the
sortWithmethod of theArrayBuffer[T]class, which is inherited from theSeqLiketrait.The following code snippet sorts an
ArrayBuffer[T]object in ascending order:Note that this does not mutate the actual
ArrayBuffer, but creates a new one with the elements in the right order.If you are using Scala 2.7, you could use the
stableSortmethod of theSortingobject. This takes the elements of theArrayBufferand produces an array of elements sorted in the right order (given by a closure as an argument, ascending as a default).For example:
The important question is what do you want to do with the
ArrayBuffer. Usually, aBufferis used internally in different algorithms in order to increase the performance of intermediate results. If you are using it for that, have a look at the ways of sorting the collection you want to return at the end of your algorithm. TheSortingobject already provides a way of transforming anArrayBufferinto a sortedArray.From the scaladoc of the
Bufferclass:As you are using it with
Actors, it might be used for some kind of actor queue – in which case, you might want to have a look at theQueuecollection.Hope it helps,
— Flaviu Cipcigan