Sorting a List of Custom Objects by Nested Properties in Java - Unexpected NullPointerException
I can't seem to get I'm attempting to set up I'm deploying to production and I've searched everywhere and can't find a clear answer... I'm currently working on a Java application where I need to sort a list of custom objects based on a nested property. My custom object, `Person`, has a property `Address`, which in turn has a `city` field. However, I'm getting a `NullPointerException` when I attempt to sort the list using a comparator that accesses `Address.city`. Hereโs a simplified version of my `Person` class and the sorting code: ```java public class Address { private String city; public Address(String city) { this.city = city; } public String getCity() { return city; } } public class Person { private String name; private Address address; public Person(String name, Address address) { this.name = name; this.address = address; } public Address getAddress() { return address; } } ``` I tried sorting the list like this: ```java List<Person> people = new ArrayList<>(); people.add(new Person("Alice", new Address("New York"))); people.add(new Person("Bob", null)); // This one has a null address people.add(new Person("Charlie", new Address("Los Angeles"))); Collections.sort(people, Comparator.comparing(person -> person.getAddress().getCity())); ``` When I run this code, I get a `NullPointerException` for the `Bob` entry because `getAddress()` returns `null`. Ideally, I want to sort the list, but if the `Address` is `null`, Iโd like those entries to appear last in the sorted list. Iโve tried adding a check in the comparator, but it didnโt resolve the issue. How can I modify my comparator to handle `null` addresses gracefully? Is there a best practice for sorting when dealing with potentially null nested properties? My development environment is Windows. Is there a better approach? I'm working with Java in a Docker container on Ubuntu 22.04. How would you solve this? Could someone point me to the right documentation? My development environment is Ubuntu 20.04. Is this even possible?