How to sort a list of classes that contain nested classes using custom comparison logic in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

class Address {
    String city;
    int zip;

    Address(String city, int zip) {
        this.city = city;
        this.zip = zip;
    }
}

class Person {
    String name;
    int age;
    Address address;

    Person(String name, int age, Address address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }
}

public class Main {

    static void printPersons(List<Person> people) {
        for (Person p : people) {
            System.out.println(
                p.name +
                " | age: " + p.age +
                " | city: " + p.address.city +
                " | zip: " + p.address.zip
            );
        }
    }

    static void sortPersons(List<Person> people) {
        people.sort(
            Comparator.comparing((Person p) -> p.address.city)
                      .thenComparing(p -> p.address.zip)
                      .thenComparing(p -> p.age)
        );
    }

    public static void main(String[] args) {

        List<Person> people = new ArrayList<>();
        people.add(new Person("Alice", 30, new Address("San Francisco", 42100)));
        people.add(new Person("Bob",   40, new Address("Austin",        32000)));
        people.add(new Person("Carol", 35, new Address("New York City", 42000)));
        people.add(new Person("Dave",  25, new Address("Austin",        32000)));
        people.add(new Person("Eve",   28, new Address("New York City", 61000)));

        sortPersons(people);
        printPersons(people);
    }
}


/*
run:

Dave | age: 25 | city: Austin | zip: 32000
Bob | age: 40 | city: Austin | zip: 32000
Carol | age: 35 | city: New York City | zip: 42000
Eve | age: 28 | city: New York City | zip: 61000
Alice | age: 30 | city: San Francisco | zip: 42100

*/


 



answered Sep 1 by avibootz
edited Sep 1 by avibootz

Related questions

...