I have a list of POJOs I need to sort somehow. I define a Comprator
inside the POJO class and use it to sort the list.
Is the following way correct/best practice? Is there a better way to do it?
public class CompratorTest { public static void main(String[] args) { List<Person> people = List.of( new Person("zoe", "saturday", 40), new Person("luca", "red", 15), new Person("boris", "vin", 54), new Person("boris", "apple", 33), new Person("boris", "apple", 70) ); List<Person> sortedPeople = people.stream() .sorted((person, other) -> Person.COMPARATOR.compare(person, other)) .collect(Collectors.toList()); sortedPeople.forEach(System.out::println); } @Data @AllArgsConstructor static class Person { final static Comparator<Person> COMPARATOR = Comparator.comparing((Person person) -> person.getName()) .thenComparing(person -> person.getSurname()) .thenComparing(person -> person.getAge()); String name; String surname; int age; }}
Output is correct, by the way.
EDITAdding a more classic way:
@Data @AllArgsConstructor static class Animal implements Comparable<Animal> { String name; String race; @Override public int compareTo(Animal other) { if (this.name.equals(other.name)) { return String.CASE_INSENSITIVE_ORDER.compare(this.race, other.race); } return String.CASE_INSENSITIVE_ORDER.compare(this.name, other.name); } }
Which one do you think is a better solution?