Sorting objects in Java requires a clear set of rules. This project explores the Comparator Interface and the Objects.compare utility. We simulate an event planning scenario where Person objects must be ordered alphabetically by their names. By decoupling the comparison logic from the data class itself, we create a flexible and robust system that can be easily extended for different sorting criteria in the future.
- Custom Comparator: Implemented
PersonByNameComparatorto define alphabetical logic. - Null-Safe Comparison: Used
Objects.compare()which provides a safe way to handle object interactions. - Logic Branching: Developed a verdict system to interpret the integer result of the comparison (
< 0,> 0, or0). - Clean Code Standards: Followed the package-per-feature structure and provided clear documentation.
- Java 8+ (Comparator API, Utility Classes)
- Person: A simple model holding the name.
- PersonByNameComparator: The logic engine for alphabetical comparison.
- EventApp: The main orchestrator that compares attendees and displays the result.
Comparison Verdict: Anna comes before Bob
Project Structure:
JavaBasics_Task_478/
├── src/
│ └── com/yurii/pavlenko/
│ ├── app/
│ │ └── EventApp.java
│ └── event/
│ ├── comparators/
│ │ └── PersonByNameComparator.java
│ └── models/
│ └── Person.java
├── LICENSE
├── TASK.md
├── THEORY.md
└── README.md
Code
package com.yurii.pavlenko.app;
import com.yurii.pavlenko.event.comparators.PersonByNameComparator;
import com.yurii.pavlenko.event.models.Person;
import java.util.Objects;
public class EventApp {
public static void main(String[] args) {
Person anna = new Person("Anna");
Person bob = new Person("Bob");
PersonByNameComparator nameComparator = new PersonByNameComparator();
int result = Objects.compare(anna, bob, nameComparator);
System.out.print("Comparison Verdict: ");
if (result < 0) {
System.out.println(anna + " comes before " + bob);
} else if (result > 0) {
System.out.println(bob + " comes before " + anna);
} else {
System.out.println("Names match.");
}
}
}package com.yurii.pavlenko.event.models;
public class Person {
private final String personName;
public Person(String personName) {
this.personName = personName;
}
public String getPersonName() {
return personName;
}
@Override
public String toString() {
return personName;
}
}package com.yurii.pavlenko.event.comparators;
import com.yurii.pavlenko.event.models.Person;
import java.util.Comparator;
public class PersonByNameComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
return p1.getPersonName().compareTo(p2.getPersonName());
}
}This project is licensed under the MIT License.
Copyright (c) 2026 Yurii Pavlenko
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files...
License: MIT