Skip to content

Optional homework (Olga Li) #46

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 61 additions & 2 deletions src/test/java/option/OptionalExample.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@

public class OptionalExample {

private static final String other = "other";
private static final String ABC = "abc";

@Test
public void get() {
final Optional<String> o1 = Optional.empty();
Expand Down Expand Up @@ -50,9 +53,65 @@ public void map() {
assertEquals(expected, actual);
}

@Test
public void orElse() {
Optional<String> o1 = getOptional();

String expected = o1.orElse(other);

String actual = o1.isPresent() ? o1.get() : other;

assertEquals(expected, actual);
}

@Test
public void orElseGet() {
Optional<String> o1 = getOptional();

String expected = o1.orElseGet(() -> other);

String actual = o1.isPresent() ? o1.get() : other;

assertEquals(expected, actual);
}

@Test
public void filter() {
Optional<String> o1 = getOptional();

Optional<String> expected = Optional.of(ABC);

Optional<String> actual = o1.filter(s -> s.equals(ABC));

if (!o1.isPresent()) {
expected = Optional.empty();
}

assertEquals(expected, actual);
}

@Test
public void flatMap() {
Optional<String> o1 = getOptional();

Function<String, Optional<String>> firstChar = s -> Optional.of(s.substring(0, 1));

Optional<String> expected = o1.flatMap(firstChar);

Optional<String> actual;

if (o1.isPresent()) {
actual = firstChar.apply(o1.get());
} else {
actual = Optional.empty();
}

assertEquals(expected, actual);
}

private Optional<String> getOptional() {
return ThreadLocalRandom.current().nextBoolean()
? Optional.empty()
: Optional.of("abc");
? Optional.empty()
: Optional.of(ABC);
}
}