How to order a list of objects as per custom order guidelines?

60 views Asked by At
data class User(
    val name: String,
    val address: Address,
    val group: String
)

data class Address(
    val street: String,
    val city: String
)

I have a list of users. I need to order this list by custom order as per guidelines in Kotlin (or Java).

  1. First order by group as below group order. (It's not alphabetical order)

    • Maths
    • Science
    • English
    • other all values in the bottom without order
  2. Then order by city as below city order. (It's not in alphabetical order)

    • Sydney
    • Adelaide
    • Melbourne
    • other all values in the bottom without order
  3. Then order by street in reverse alphabetical order

  4. Then order by name in alphabetical order

How can I write Comparator or custom method to order list as per above guidelines? Address class can move into User class if needed.

1

There are 1 answers

0
Vlad Lavrovsky On

you need to implement Comparable in class User like so

    class User
implements Comparable{
    String name;
    Address address;
    String group;
    Integer groupRank = Integer.valueOf(7);
    Integer addressRank = Integer.valueOf(7);
    public User(String name, Address address, String group)
    {
        this.name = name;
        this.address = address;
        this.group = group;
        if (group.equals("Maths"))groupRank = 1;
        if (group.equals("Science"))groupRank = 2;
        if (group.equals("English"))groupRank = 3;

        // this should be moved into the Address class
        if (address.city.equals("Sydney"))addressRank = 1;
        if (address.city.equals("Adelaide"))addressRank = 2;
        if (address.city.equals("Melbourne"))addressRank = 3;
    }

    public int compareTo(Object o) {
        // do something if o is not User
        User other = (User) o;
        int groupCompare = this.groupRank.compareTo(other.groupRank);
        
        // Address class should implement Comparable and have its own compreTo 
        if (groupCompare != 0)return groupCompare;
        else return this.addressRank.compareTo(other.addressRank);
    }
}
class Address{
    String city;
    String street;
}