Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,102 questions

55,976 answers

573 users

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

1 Answer

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

public class SortNestedStructs {

    // Inner Record
    public record Address(String city, int zipCode) {}

    // Outer Record
    public record Person(String name, int age, Address address) {}

    /**
     * Sorts a list of Person objects in-place:
     * 1. City (Ascending, Case-Insensitive)
     * 2. ZipCode (Ascending)
     * 3. Age (Ascending)
     */
    public static void sortPeople(List<Person> people) {
        Comparator<Person> personComparator = Comparator
                .comparing((Person p) -> p.address().city(), String.CASE_INSENSITIVE_ORDER)
                .thenComparingInt(p -> p.address().zipCode())
                .thenComparingInt(Person::age);

        people.sort(personComparator);
    }

    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();

        people.add(new Person("Bob", 28, new Address("New York City", 62000)));
        people.add(new Person("Dave", 40, new Address("Austin", 32000)));
        people.add(new Person("Carol", 32, new Address("New York City", 34000)));
        people.add(new Person("Alice", 30, new Address("San Francisco", 42100)));
        people.add(new Person("Eve", 35, new Address("Austin", 32000)));

        sortPeople(people);

        // Print results
        for (Person p : people) {
            System.out.printf("%-8s | Age: %d | City: %-15s | Zip: %d%n",
                    p.name(), p.age(), p.address().city(), p.address().zipCode());
        }
    }
}
 

/*
run:
 
Eve      | Age: 35 | City: Austin          | Zip: 32000
Dave     | Age: 40 | City: Austin          | Zip: 32000
Carol    | Age: 32 | City: New York City   | Zip: 34000
Bob      | Age: 28 | City: New York City   | Zip: 62000
Alice    | Age: 30 | City: San Francisco   | Zip: 42100
 
*/

 



answered Sep 1 by avibootz
edited Sep 1 by avibootz

Related questions

...