Это решение похоже на @ ответ Джейсона , но использует немного другой контракт. Это похоже на то, как он определяет класс для представления результата оценки производительности. Он отличается по форме тем, что позволяет определять карту факторов для оценки эффективности.
Ideone demo
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class Main {
public static void main(final String... args) {
final String FORMAT = "Performance %s\nbonus %d";
final Map<Double, PerformanceResult> performanceResultMap = new HashMap<>();
performanceResultMap.put(2.0, new PerformanceResult("Excellent", 1000));
performanceResultMap.put(1.5, new PerformanceResult("Fine", 500));
performanceResultMap.put(1.0, new PerformanceResult("Satisfactory", 100));
final PerformanceResult excellent =
calculatePerformance(200.0, 100.0, performanceResultMap);
System.out.println(String.format(FORMAT, excellent.getMessage(), excellent.getBonus()));
final PerformanceResult fine = calculatePerformance(150.0, 100.0, performanceResultMap);
System.out.println(String.format(FORMAT, fine.getMessage(), fine.getBonus()));
final PerformanceResult satisfactory =
calculatePerformance(100.0, 100.0, performanceResultMap);
System.out.println(String.format(FORMAT, satisfactory.getMessage(), satisfactory.getBonus()));
try {
calculatePerformance(0, 100, performanceResultMap);
throw new IllegalStateException("Exception should have been thrown");
} catch (final NoFittingPerformanceResultFoundException e) {
System.out.println("Expected exception thrown");
}
}
public static PerformanceResult calculatePerformance(
final double actual,
final double target,
final Map<Double, PerformanceResult> performanceResultMap) {
return performanceResultMap.keySet().stream()
.sorted(Collections.reverseOrder())
.filter(factor -> actual >= target * factor)
.findFirst()
.map(performanceResultMap::get)
.orElseThrow(NoFittingPerformanceResultFoundException::new);
}
}
class PerformanceResult {
private final String message;
private final int bonus;
PerformanceResult(final String message, final int bonus) {
this.message = Objects.requireNonNull(message);
this.bonus = bonus;
}
public String getMessage() {
return message;
}
public int getBonus() {
return bonus;
}
}
class NoFittingPerformanceResultFoundException extends IllegalStateException {}