Last active
September 19, 2018 18:47
-
-
Save thiagomarinho/3aede5db16f4382c61c6394b9aa96da0 to your computer and use it in GitHub Desktop.
Picker using Optional
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.List; | |
import java.util.Optional; | |
import java.util.function.Function; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
public class Picker<T> { | |
private List<Optional<T>> options; | |
@SafeVarargs | |
public static <T> Picker<T> of(Optional<T>... options) { | |
return new Picker<T>(options); | |
} | |
private Picker(Optional<T>[] options) { | |
this.options = Stream.of(options).collect(Collectors.toList()); | |
} | |
public <A> Optional<A> get(Class<A> type, Function<T, Optional<A>> function) { | |
for (Optional<T> option : options) { | |
if (option.isPresent()) { | |
Optional<A> result = function.apply(option.get()); | |
if (result.isPresent()) { | |
return result; | |
} | |
} | |
} | |
return Optional.empty(); | |
} | |
} |
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 static org.junit.jupiter.api.Assertions.assertEquals; | |
import java.util.Optional; | |
import org.junit.jupiter.api.Test; | |
public class PickerTest { | |
@Test | |
public void test() { | |
Optional<TestingClass> empty = Optional.empty(); | |
Optional<TestingClass> first = Optional.of(new TestingClass()); | |
Optional<TestingClass> second = Optional.of(new TestingClass("one")); | |
Optional<TestingClass> third = Optional.of(new TestingClass("another")); | |
Optional<String> optional = Picker.of(empty, first, second, third).get(String.class, selected -> { | |
return Optional.ofNullable(selected.getName()); | |
}); | |
assertEquals("one", optional.get()); | |
} | |
private static class TestingClass { | |
private String name; | |
public TestingClass() { | |
} | |
public TestingClass(String name) { | |
this.name = name; | |
} | |
public String getName() { | |
return name; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackoverflow.com/questions/32776705/whats-the-most-elegant-way-to-combine-optionals