Skip to content
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

homework #22

Open
wants to merge 2 commits 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
60 changes: 57 additions & 3 deletions src/test/java/option/OptionalExample.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package option;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;

import static org.junit.Assert.assertEquals;
import java.util.function.Predicate;

public class OptionalExample {

Expand All @@ -18,7 +19,7 @@ public void get() {

o1.orElse("t");
o1.orElseGet(() -> "t");
o1.orElseThrow(() -> new UnsupportedOperationException());
// o1.orElseThrow(() -> new UnsupportedOperationException());
}

@Test
Expand Down Expand Up @@ -55,4 +56,57 @@ private Optional<String> getOptional() {
? Optional.empty()
: Optional.of("abc");
}

@Test
public void filter(){

final Optional<String> o1 = getOptional();

final Predicate<String> lenIs3 = string -> string.length() == 3;

final Optional<String> expected = o1.filter(lenIs3);

final Optional<String> actual;

if(o1.isPresent() && lenIs3.test(o1.get()))
actual = Optional.of(o1.get());
else
actual = Optional.empty();

assertEquals(expected, actual);
}

@Test
public void flatMap(){

final Optional<String> o1 = getOptional();

final Function<String, Optional<String>> func = Optional::of;

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

final Optional<String> actual;

if(o1.isPresent())
actual = func.apply(o1.get());
else actual = Optional.empty();

assertEquals(expected, actual);
}

@Test
public void orElse(){

final Optional<String> o1 = getOptional();

final String expected = o1.orElse("orElse");

final String actual;

if(o1.isPresent())
actual = o1.get();
else actual = "orElse";

assertEquals(expected, actual);
}
}