Reputation: 21
I have a problem with Java 8 if statements. Can someone show me a way to write this code without if's using only Java 8 lambdas? The solution shouldn't have if's, while's or for's. Is it even possible?
if (first_number == second_number) {
return "PERFECT";
} else if (first_number > second_number) {
return "ABUNDANT";
} else {
return "DEFICIENT";
}
Upvotes: 1
Views: 7084
Reputation: 56
How about this solution with lambdas? I'm assuming integer values, but shouldn't be too hard to switch to float or double.
int first_number = 10;
int second_number = 20;
IntBinaryOperator subtract = (n1, n2) -> n1 - n2; // Subtract second from first value
IntUnaryOperator determineSign = n -> Integer.signum(n); // Determine the sign of the subtraction
IntFunction<String> message = key -> { // Sign of 0 means value has been 0 (first_number == second_number). Sign of 1 = positive value, hence equals first_number > second_number, otherwise return the default.
Map<Integer, String> messages = new HashMap<>();
messages.put(0, "PERFECT");
messages.put(1, "ABUNDANT");
return messages.getOrDefault(key, "DEFICIENT");
};
return message.apply(determineSign.applyAsInt(subtract.applyAsInt(first_number, second_number)));
Edit: Andreas mentioned valid concerns, I agree you wouldn't do it like that. But I think its more about proving that it is possible using lambdas. :) Another method (ab)using Optional:
int first_number = 20;
int second_number = 20;
Optional<Integer> dummy = Optional.of(0); // Dummy allowing to call filter on the Optional
Predicate<Integer>isAbundant = i -> first_number > second_number; // Check if input is abundant
Predicate<Integer> isPerfect = i -> first_number == second_number; // Check if input is perfect
Supplier<String> other = () -> dummy.filter(isAbundant).map(i -> "ABUNDANT").orElse("DEFICIENT"); // Fallback, if input is not perfect. Check for abundant or return default
Supplier<String> validate = () -> dummy.filter(isPerfect).map(i -> "PERFECT").orElse(other.get()); // Check if input is perfect or use fallback
return validate.get();
Upvotes: 0
Reputation: 159145
No "if's, while's or for's", but no lambdas either:
return (first_number == second_number ? "PERFECT" :
first_number > second_number ? "ABUNDANT" : "DEFICIENT");
The ? :
is called the conditional operator in the Java Language Specification (see 15.25. Conditional Operator ? :
), but is commonly known as the ternary operator, since it is the only operator in Java with 3 parts.
Upvotes: 7