Created
February 15, 2020 05:53
-
-
Save ksundong/47ba7da544f0d4a3f2052e043c548dc5 to your computer and use it in GitHub Desktop.
Optional map() and flatMap() difference
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 org.junit.jupiter.api.BeforeEach; | |
import org.junit.jupiter.api.Test; | |
import java.util.Optional; | |
import static org.assertj.core.api.Assertions.assertThat; | |
class MapAndFlatMapTest { | |
Person dion; | |
@BeforeEach | |
void setUp() { | |
dion = new Person("dion", 26); | |
} | |
@Test | |
void wrapWithOptionalTest() throws Exception { | |
Optional<Person> personOptional = Optional.of(dion); | |
Optional<Optional<String>> nameOptionalWrapper = personOptional.map(Person::getOptionalName); | |
Optional<String> nameOptional = nameOptionalWrapper.orElseThrow(Exception::new); | |
String name = nameOptional.orElse(""); | |
assertThat(name).isEqualTo("dion"); | |
String name2 = personOptional.flatMap(Person::getOptionalName).orElse(""); | |
assertThat(name2).isEqualTo("dion"); | |
} | |
@Test | |
void normalParameterTest() { | |
Optional<Person> personOptional = Optional.of(dion); | |
Optional<Integer> integerOptional = personOptional.map(Person::getAge); | |
Integer age = integerOptional.orElse(0); | |
assertThat(age).isEqualTo(26); | |
Integer age2 = personOptional.flatMap(p -> Optional.ofNullable(p.getAge())).orElse(0); | |
assertThat(age2).isEqualTo(26); | |
} | |
} |
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; | |
public class Person { | |
private final String name; | |
private final Integer age; | |
public Person(String name, Integer age) { | |
this.name = name; | |
this.age = age; | |
} | |
public Optional<String> getOptionalName() { | |
return Optional.ofNullable(this.name); | |
} | |
public Integer getAge() { | |
return this.age; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment