javacomparable

How to compare two properties of a class


There is a class Movie which has two properties, id and type.

static class Movie implements Comparable<Movie> {
    Integer id;
    Type type;

    Movie(Integer id, Type type) {
        this.id = id;
        this.type = type;
    }

    @Override
    public int compareTo(final Movie other) {
        return 0;
    }

    public Integer getId() {
        return id;
    }

    public Type getType() {
        return type;
    }
}

enum Type {
    TYPE_A,
    TYPE_B
}

Let's say that this is the input:

// MOVIE_ID  MOVIE_TYPE
// 1         TYPE_A
// 2         TYPE_B
// 3         TYPE_A
// 4         TYPE_B

and the output I want to achieve is this:

// MOVIE_ID  MOVIE_TYPE
// 1         TYPE_A
// 3         TYPE_A
// 2         TYPE_B
// 4         TYPE_B

Also I want to be sure that null is greater. Are there any libraries or do I need to implement it by my own, if so, what's the best way to achieve that?


Solution

  • So you want to compare by type first, and then by ID? In that case, you need some compareTo logic like this:

    if (type != other.type) {
        return type.compareTo(other.type);
    } else {
        return id.compareTo(other.id);
    }
    

    To account for null, you could add more ifs.