sorting - How to sort by two fields in Java? -
i have array of objects person ( int age; string name;)
.
how sort array persons going alphabetically sorted , age ?
which algorithm ?
you can use collections.sort
follows:
private static void order(list<person> persons) { collections.sort(persons, new comparator() { public int compare(object o1, object o2) { string x1 = ((person) o1).getname(); string x2 = ((person) o2).getname(); int scomp = x1.compareto(x2); if (scomp != 0) { return scomp; } else { integer x1 = ((person) o1).getage(); integer x2 = ((person) o2).getage(); return x1.compareto(x2); } }}); }
list<persons>
sorted name, age.
string.compareto
"compares 2 strings lexicographically" - docs.
collections.sort
static method in native collections library. actual sorting, need provide comparator defines how 2 elements in list should compared: achieved providing own implementation of compare
method.
Comments
Post a Comment