Posts Tagged ‘JavaFX Sequences Sort objects’

JavaFx how to sort a sequence of objects

June 11, 2010

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;
        p1.sname.compareTo(p2.sname);
    }
}

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.