Search code examples
javaif-statementrangecode-duplication

Is there a more efficient way to write multiple if else?


I need to match the average score to a letter grade. That means

if (90 < avg && avg < 100) {
     return 'A';
} 

and so on until 'F', with 5 if-else statements.

That's a lot of repetition, and the ranges I'm matching to are of the same length.

Is there a more efficient way to do this? I don't want to repeat the if-else statement 5 times.


Solution

  • You may find this approach verbose and overengineered. Yes, it's.

    Though, I like the way the grading system is defined.

    class Test {
      public static void main(String[] args) {
        Map<String, Predicate<Integer>> gradingSystem = new HashMap<>();
    
        gradingSystem.put("A", mark -> mark >= 90 && mark <= 100);
        gradingSystem.put("B", mark -> mark >= 80 && mark < 90);
    
        translateScoreIntoGrade(86, gradingSystem); // B
        translateScoreIntoGrade(95, gradingSystem); // A
      }
    
      public static String translateScoreIntoGrade(int score, Map<String, Predicate<Integer>> gradingSystem) {
        return gradingSystem.entrySet().stream()
            .filter(gradePredicate -> gradePredicate.getValue().test(score))
            .findFirst()
            .map(Map.Entry::getKey)
            .orElseThrow(() -> new IllegalArgumentException("This grade isn't valid for this system!"));
      }
    }