Topic Overview

Welcome to our exploration of sorted maps using custom classes and comparators in Java. In today's lesson, we'll learn how to use custom classes as keys in sorted maps. This approach enhances data organization and access. With the addition of comparators, we can dictate the order in such maps.

Quick Recap on Sorted Maps

A sorted map is a dictionary with its keys always in order. This arrangement makes operations like searching for keys within a range more efficient. In Java, we use the TreeMap class to create sorted maps:

import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        TreeMap<String, Integer> sMap = new TreeMap<>();
        sMap.put("a", 1);
        sMap.put("b", 2);
        sMap.put("c", 3);
        
        System.out.println(sMap);  // Outputs {a=1, b=2, c=3}
    }
}
Introduction to Custom Classes in Java

Custom classes enable us to create objects that fit our data — for instance, a Person class for employee information or a Book class for a library database. In Java, classes are the blueprints for creating objects.

Consider this simple class, for example:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public static void main(String[] args) {
        Person person = new Person("John Doe", 30);
        System.out.println(person.getName());  // Outputs "John Doe"
        System.out.println(person.getAge());   // Outputs 30
    }
}
Using Custom Classes as Keys in Sorted Maps

Using custom classes as map keys helps organize complex multivariate keys in a sorted map. Consider the following example using the Person class as a key in a sorted map (i.e., TreeMap). However, this will not work yet.

import java.util.TreeMap;

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

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

    // Getters and other methods...

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

        Person john = new Person("John", 30);
        Person alice = new Person("Alice", 25);

        people.put(john, "Programmer");
        people.put(alice, "Designer");
    }
}

We can see here that John is assigned the value "Programmer", and Alice is assigned the value "Designer." However, this code will produce a ClassCastException. The reason is that the TreeMap needs a way to compare the Person objects to maintain its order.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal