Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java sort based on two columns

Lets say I have table like this:

 String | Int1 | Int2
 "foo"    5      0
 "faa"    4      1
 "zaa"    0      1
 "zoo"    4      2
 "laa"    4      3
 "loo"    1      4

What I would like to get is table like this:

 String | Int1 | Int2
 "foo"    5      0
 "laa"    4      3
 "zoo"    4      2
 "faa"    4      1
 "loo"    1      4
 "zaa"    0      1

First thing that happens is sort based on column Int1.

Second thing that happens is sort of based on column Int2 but only on rows that have same numbers in column Int1

How should I approach this problem without using any database engine?

like image 604
MatBanik Avatar asked Jul 29 '11 19:07

MatBanik


1 Answers

You'd normally do this with a List<Item> where Item is a type containing all three values ("foo", 5, 0 for the first row, for example).

You'd then write a Comparator<Item> which compared the Int1 values of the two Item objects presented to it in compare, and if that gave a definite answer, returned that answer... and otherwise compared the Int2 values.

like image 63
Jon Skeet Avatar answered Oct 01 '22 18:10

Jon Skeet