Damir Damir - 8 months ago 19
Java Question

How to sort by two fields in Java?

I have array of objects

person ( int age; String name;)

How to sort this array that persons are going alphabetically sorted , then by age ?

Which algorithm is for this ?


You can use Collections.sort as 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> is now sorted by name, then by age.

String.compareTo "Compares two strings lexicographically" - from the docs.

Collections.sort is a static method in the native Collections library. It does the actual sorting, you just need to provide a Comparator which defines how two elements in your list should be compared: this is achieved by providing your own implementation of the compare method.