Last active
August 29, 2015 13:59
-
-
Save zaltoprofen/10458835 to your computer and use it in GitHub Desktop.
This file contains 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.Optional; | |
import java.util.function.Consumer; | |
public class Application1 { | |
public static void main (String[] args) { | |
let(new ArrayWrapper<String>(args), a ->{ | |
System.out.println(fullName(a.get(0), a.get(1)).orElse("Failure")); | |
}); | |
} | |
public static Optional<String> fullName(Optional<String> firstName, Optional<String> familyName){ | |
return firstName.flatMap( first -> familyName.map( family -> String.format("%s %s",first, family))); | |
} | |
static <T> void let(T obj, Consumer<T> body){ | |
body.accept(obj); | |
} | |
} | |
class ArrayWrapper<T>{ | |
private T[] array; | |
public ArrayWrapper(T[] array){ | |
this.array = array; | |
} | |
public Optional<T> get(int index){ | |
try{ | |
return Optional.of(array[index]); | |
}catch(ArrayIndexOutOfBoundsException e){ | |
return Optional.empty(); | |
} | |
} | |
} | |
// Results: | |
// $ java Application1 John | |
// Failure | |
// $ java Application1 John Doe | |
// John Doe |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment