Last active
April 8, 2018 02:13
-
-
Save m-x-k/e0460b7f453cb33068af397949772cbf to your computer and use it in GitHub Desktop.
Validation Example with BiFunction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.function.BiFunction; | |
import java.util.function.Function; | |
import static Pet.*; | |
public class BiFunctionValidationExample { | |
public static void main(String[] args) { | |
// BiFunction example | |
BiFunctionValidation<Pet, String> v = new BiFunctionValidation<>(IS_EMPTY_RETURN_PET); | |
System.out.println(v.validate(null, CAT)); // prints CAT | |
System.out.println(v.validate(null, DOG)); // prints DOG | |
System.out.println(v.validate("VALUE", DOG)); // prints null | |
// Function example | |
System.out.println(GET_PET.apply("dog")); | |
} | |
} | |
enum Pet { | |
CAT, | |
DOG; | |
/* | |
* Return Pet if String value is null | |
*/ | |
public static BiFunction<Pet, String, Pet> IS_EMPTY_RETURN_PET = (x, y) -> { | |
if (y == null) | |
return x; | |
return null; | |
}; | |
/* | |
* Return Pet matching string | |
*/ | |
public static Function<String, Pet> GET_PET = (x) -> valueOf(x.toUpperCase()); | |
} | |
/* | |
* BiFunctionValidation<RETURN_OBJECT, VALUE_OBJECT> | |
*/ | |
class BiFunctionValidation<R, V> { | |
private BiFunction<R, V, R> biFunction; | |
public BiFunctionValidation(BiFunction<R, V, R> biFunction) { | |
this.biFunction = biFunction; | |
} | |
public R validate(V value, R r) { | |
return biFunction.apply(r, value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment