1

I have the class below and I want to be able to determine a senior role between two dtos that is passed. The enum Role below is arranged according to seniority. Secretary is higher than cleaner and Manager is higher than secretary and cleaner.

How do I determine which Role is higher and return in the jobFunction?

        @Table(name = "myusers_v")
        public class UserDto {

            @Column(name = "JOB_FUNCTION")
            @Enumerated(EnumType.STRING)
            private Role jobFunction;

            public static UserDto merge(UserDto userDto1, UserDto userDto2) {

                //Assuming userDto1.getJobFunction() = Cleaner
                //Assuming userDto2.getJobFunction() = Manager

                //? Determine which role is higher from the two above and return below

                return UserDto.builder()
                        .jobFunction(defaultIfNull(userDto1.getJobFunction(), userDto2.getJobFunction()))
                        .build();
            }

        }


        public enum Role {
          Cleaner, Secretary, Manager, Director; 
        }
Baba
  • 2,059
  • 8
  • 48
  • 81
  • I would add a field to the enum to be a kind of sort order, then you can add extras later if required. You should not rely on the ordinal value of the enum to do this. – jr593 Jul 19 '18 at 14:17

3 Answers3

1

Enum types are Comparable, and the order is based on their ordinal (i.e., Secretary > Cleaner), which simply means that you don't need any additional comparison logic.

You can just use:

Role greater = userDto1.getJobFunction()
   .compareTo(userDto2.getJobFunction()) > 0 ?
      userDto1.getJobFunction() : userDto2.getJobFunction();
    //well, this doesn't deal with the case of equal roles.

return UserDto.builder()
          .jobFunction(greater)
          .build();

The above uses the Comparable.compareTo (see docs here) method to determine which of the two roles is greater, then select its corresponding object.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
0

You can add a member to your enum to let your code readable

public enum Role {
        CLEANER  (1), 
        SECRETARY(2), 
        MANAGER  (3), 
        DIRECTOR (4); 

        private final int level;

        Role(int level) {
            this.level = level;
        }

        public int getLevel() {
            return this.level;
        }
    }

And just test by level:

if ( userDto1.getJobFunction().getLevel() > userDto2.getJobFunction().getLevel() ) {
 ...
}
Halayem Anis
  • 7,654
  • 2
  • 25
  • 45
-1

Either number them like this:

public enum Role {
    Cleaner = 0,
    Secretary = 1,
    Manager = 2,
    Director = 3;
}

(But I'm not sure if you can compare them like this)

Or, try Ordinal

userDto1.ordinal > UserDto2.ordinal
KYL3R
  • 3,877
  • 1
  • 12
  • 26