tehvan tehvan - 10 months ago 60
Java Question

Sortable table-like Java class

Does anyone know of a class in Java that has a list of elements, so that the elements are sortable by any of the elements members?
The idea is basically to have some database table-like implementation, where you can just add fields to sort by. To illustrate:

SomeTable table = new SomeTable();
table.addField("name", String);
table.addField("age", int);
table.addField("hair color", String);
table.add(new Object[]{"Thomas", 32, "brown"});
table.add(new Object[]{"Jack", 34, "black"});

would sort the table so that Thomas is the first element, while
would sort the table so that Jack is the first element.

I can code something like this myself (actually I have done that once), but I'm just curious to see if there's a ready library to do such things (without a database).

PS: I know that
is not a class, but that's not the point here. This example code is just here to show the kind of functionality I expect.


The closest thing I can think of myself is the Apache Commons BeanUtils API. For example for a "student" table.

  DynaProperty[] props = new DynaProperty[]{
        new DynaProperty("firstName", String.class),
        new DynaProperty("lastName",  String.class),
        new DynaProperty("address", java.util.Map.class)

    BasicDynaClass dynaClass = new BasicDynaClass("student", null, props);

Given a collection table of these student objects. We define a BeanComparator

 BeanComparator surnameComparator
        = new BeanComparator("lastname");
Collections.sort(table, surnameComparator);

Not sure if this is what you're looking for, but it seems pretty close.