Skip to content

Instantly share code, notes, and snippets.

@zaltoprofen
Last active August 29, 2015 13:59
Show Gist options
  • Save zaltoprofen/10458835 to your computer and use it in GitHub Desktop.
Save zaltoprofen/10458835 to your computer and use it in GitHub Desktop.
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