fork download
  1. import java.time.LocalDateTime;
  2. import java.math.BigInteger;
  3. import java.util.Arrays;
  4. import java.util.List;
  5. import java.util.function.Consumer;
  6. import java.util.function.Function;
  7. import java.util.stream.Stream;
  8.  
  9. class Untitled {
  10. public static void main(String[] args) {
  11. List<ExclusiveField> exclusiveFields = Arrays.asList(
  12. ExclusiveField.withBigIntegerValue(BigInteger.ONE),
  13. ExclusiveField.withDateValue(LocalDateTime.now()),
  14. ExclusiveField.withStringValue("ABC")
  15. );
  16.  
  17. for(ExclusiveField field : exclusiveFields) {
  18. field.consume(
  19. i -> System.out.println("Value was a BigInteger: " + i),
  20. d -> System.out.println("Value was a LocalDateTime: " + d),
  21. s -> System.out.println("Value was a String: " + s)
  22. );
  23. }
  24. }
  25. }
  26. interface ExclusiveField {
  27. static ExclusiveField withBigIntegerValue(BigInteger i) {
  28. return (biM, dM, sM) -> biM.accept(i);
  29. }
  30. static ExclusiveField withDateValue(LocalDateTime d) {
  31. return (biM, dM, sM) -> dM.accept(d);
  32. }
  33. static ExclusiveField withStringValue(String s) {
  34. return (biM, dM, sM) -> sM.accept(s);
  35. }
  36.  
  37. void consume(
  38. Consumer<BigInteger> bigIntegerMatcher, Consumer<LocalDateTime> dateMatcher, Consumer<String> stringMatcher);
  39.  
  40. default <R> R map(
  41. Function<BigInteger, R> bigIntegerMatcher, Function<LocalDateTime, R> dateMatcher, Function<String, R> stringMatcher) {
  42.  
  43. Stream.Builder<R> b = Stream.builder();
  44. consume(adapt(bigIntegerMatcher, b),adapt(dateMatcher, b),adapt(stringMatcher, b));
  45. return b.build().findFirst().get();
  46. }
  47. static <T,R> Consumer<T> adapt(Function<T,R> f, Consumer<R> c) {
  48. return t -> c.accept(f.apply(t));
  49. }
  50. }
  51.  
Success #stdin #stdout 0.16s 2184192KB
stdin
Standard input is empty
stdout
Value was a BigInteger: 1
Value was a LocalDateTime: 2019-05-09T07:05:17.348
Value was a String: ABC