JavaFx how to sort a sequence of objects

Just a quick one, came across this “challenge” (I have a sequence of people and I want to sort by age) the other day, found the following two links which helped: one and two

Here is some example code:

class person extends Comparable
    var fname: String;
    var sname: String;
    var age: Integer;

    override function compareTo(other: Object): Integer
        return age - (other as Person).age
//With my class of person defined, I create a sequence of people

var people : Person[] =
    Person { fname: "Adam" sname: "Baxter" age: 50 }
    Person { fname: "Jill" sname: "Smith" age: 37 }
    Person { fname: "Jack" sname: "Pale" age: 17 }

//Printing this sequence presents the entries in the order they were entered:

println("Before sort");
for (i in people)
    println("{i.fname}, {i.sname}, {i.age}");

//Lets sort the sequence by age

people = Sequences.sort(people) as Person[];

//Now we just iterate over it again:

println("after sort");
for (i in people)
    println("{i.fname}, {i.sname}, {i.age}");

Ok, that is all nice and easy… How about if I want to sort by surname?

A few more lines of code and we have that one dealt with:

class MyPersonComparator extends Comparator
    override function compare(o1:Object, o2:Object)
        var p1 = o1 as Person;
        var p2 = o2 as Person;

def p = MyPersonComparator{};

people = Sequences.sort(people, p) as Person[];

println("sorted by sname");
for (i in people)
    println("{i.fname}, {i.sname}, {i.age}");

Maybe it is me, but I struggled to find anything in the official documentation on this, hence this post. Big thanks go to NikoJava and dgrieve.


One Response to “JavaFx how to sort a sequence of objects”

  1. JavaFX links of the week, June 14 // JavaFX News, Demos and Insight // FX Experience Says:

    […] itssmee has posted two posts this week, titled ‘Tutorial on how to use JavaFX 1.3 with the Twitter API‘ and ‘how to sort a sequence of objects‘. […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: