1

How can I sort a Vector of my objects in Scala? Is there some library sorting routines or do I have to write my own?

I have a class:

class Data2D(var x:Int, var y:Int)

and I am passing a vector of these to my function:

private def foo(data: Vector[Data2D]): Int = {
     data:Vector sortedOnX = // ??
}

how can I sort the vector, based on the x-values of the Data2D objects?

In java I do:

Collections.sort(data, XComparator.INSTANCE);

where XComparator is:

enum XComparator implements Comparator<Data2D> {
    INSTANCE;
    @Override
    public int compare(Data2D o1, Data2D o2) {
        if (o1.getX() <= o2.getX()) {
            return -1;
        } else {
            return 1;
        }
    }
}

1 Answer 1

6
private def foo(data: Vector[Data2D]): Int = data.sortBy(_.x)

See also the methods sortWith and sorted, as well as the methods provided by the Ordering object.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much. I would have never guess to provide "_.x" argument - as my eclipse autocompletion indicates that "sortBy()" takes no parameters.
@drozzy Weird. Scaladoc is your friend: scala-lang.org/api/current/index.html
Yeah, I find the scaladoc cryptic too :) It's just a lot of parenthesis and square brackets, I'm like o_o scala-lang.org/api/current/scala/collection/immutable/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.