Skip to content
Erich Seifert edited this page Mar 14, 2016 · 1 revision

How can I sort by a certain column?

The class de.erichseifert.gral.data.DataTable offers a sort method which can be used to sort the stored data by one or more columns.

Given the following data:

DatTable data = new DataTable(Integer.class, Double.class, Double.class);
data.add(4, 1.0, 0.0);
data.add(3, 1.0, 1.0);
data.add(2, 1.0, 2.0);
data.add(1, 3.0, 3.0);

which produces the following data structure:

col 0 col 1 col 2
4 1.0 0.0
3 1.0 1.0
2 1.0 2.0
1 3.0 3.0

Single column

Sorting the data by the first column in ascending order

data.sort(new Ascending(0));

changes the data to

col 0 col 1 col 2
1 3.0 3.0
2 1.0 2.0
3 1.0 1.0
4 1.0 0.0

Sorting the data by the second column in descending order

data.sort(new Descending(1));

changes the data to

col 0 col 1 col 2
1 3.0 3.0
4 1.0 0.0
3 1.0 1.0
2 1.0 2.0

Multiple columns

Sorting the data by the second column in descending order and on equality sorting the data by the first column in ascending order.

data.sort(new Descending(1), new Ascending(0));

changes the data to

col 0 col 1 col 2
1 3.0 3.0
2 1.0 2.0
3 1.0 1.0
4 1.0 0.0

Sorting the data by the second column in descending order and on equality sorting the data by the third column in ascending order.

data.sort(new Descending(1), new Ascending(2));

changes the data to

col 0 col 1 col 2
1 3.0 3.0
4 1.0 0.0
3 1.0 1.0
2 1.0 2.0