Skip to content

Java Object Comparison and Custom Sorting #155

@sudosf

Description

@sudosf

Background

HackerRank OOP problems (like Shopping Cart, Library Management, Vehicle Inventory) require sorted output by custom fields. Failing to sort correctly causes test failures even when logic is correct, because assertions rely on exact string comparison including order.

What to learn and implement

1. Comparable
Implement Comparable<T> on a custom class to define its natural ordering. Override compareTo(T other) to return negative, zero, or positive based on comparison. Used when the class itself defines how it should be sorted.

class Product implements Comparable<Product> {
    String name;
    public int compareTo(Product other) {
        return this.name.compareTo(other.name); // alphabetical
    }
}

2. Comparator
Use when you need multiple sort orders or can't modify the class. Pass to Collections.sort or List.sort.

list.sort(Comparator.comparing(Product::getName));
list.sort(Comparator.comparing(Product::getCategory)
         .thenComparing(Product::getName)); // multi-field sort

3. TreeMap
Automatically keeps keys sorted. Use instead of HashMap when output order matters.

Map<String, Integer> sorted = new TreeMap<>(); // alphabetical by key

4. equals and hashCode
Override both when using custom objects as HashMap keys or in HashSets. If two objects are equal by your definition, they must produce the same hashCode.

@Override
public boolean equals(Object o) { ... }

@Override
public int hashCode() {
    return Objects.hash(id, name);
}

5. Null checks for HackerRank
Add defensive null checks at the start of methods to avoid NPE on edge case inputs and improve test case pass rate.

if (s == null || s.isEmpty()) return someDefault;

Practice problems

  • Rework Shopping Cart Checkout from Nedbank mock: categories sorted alphabetically, products sorted by name
  • Rework Library Management from Nedbank mock: books sorted by title then quantity
  • LeetCode 937: Reorder Data in Log Files (custom multi-field sort)
  • LeetCode 1636: Sort Array by Increasing Frequency

References

Metadata

Metadata

Assignees

No one assigned

    Labels

    hashmapHashmap and set problemsnedbank-prepDirectly maps to Nedbank VAS assessment

    Projects

    Status
    In progress

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions