BAEL4640 Find First with Optional (#10142)

* BAEL4640 Find First with Optional

* BAEL4640 Fixes for review comments

* BAEL4640 Removing blank lines

* BAEL4640 Removing blank lines

* BAEL4640 Changes for 8.3 Optional.flatMap

Co-authored-by: Chirag Dewan <chirag.dewan@ericsson.com>
This commit is contained in:
dev-chirag 2020-10-25 16:13:22 +05:30 committed by GitHub
parent e459c3faa0
commit 679d45ca37
2 changed files with 53 additions and 11 deletions

View File

@ -1,23 +1,50 @@
package com.baeldung.nulls;
import java.util.List;
import java.util.Optional;
import static java.util.Collections.emptyList;
public class UsingOptional {
public Optional<Object> process(boolean processed) {
public static final String DEFAULT_VALUE = "Default Value";
public Optional<Object> process(boolean processed) {
String response = doSomething(processed);
return Optional.ofNullable(response);
}
private String doSomething(boolean processed) {
public String findFirst() {
return getList().stream()
.findFirst()
.orElse(DEFAULT_VALUE);
}
public Optional<String> findOptionalFirst() {
return getList().stream()
.findFirst();
}
private List<String> getList() {
return emptyList();
}
public Optional<String> optionalListFirst() {
return getOptionalList().flatMap(
list -> list.stream().findFirst());
}
private Optional<List> getOptionalList() {
return Optional.ofNullable(getList());
}
private String doSomething(boolean processed) {
if (processed) {
return "passed";
} else {
return null;
}
}
}

View File

@ -11,32 +11,47 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class UsingOptionalUnitTest {
private UsingOptional classUnderTest;
private UsingOptional dataObject;
@BeforeEach
public void setup() {
classUnderTest = new UsingOptional();
dataObject = new UsingOptional();
}
@Test
public void whenArgIsFalse_thenReturnEmptyResponse() {
Optional<Object> result = classUnderTest.process(false);
Optional<Object> result = dataObject.process(false);
assertFalse(result.isPresent());
}
@Test
public void whenArgIsTrue_thenReturnValidResponse() {
Optional<Object> result = classUnderTest.process(true);
Optional<Object> result = dataObject.process(true);
assertTrue(result.isPresent());
}
@Test
public void whenArgIsFalse_thenChainResponseAndThrowException() {
assertThrows(Exception.class, () -> classUnderTest.process(false).orElseThrow(() -> new Exception()));
assertThrows(Exception.class, () -> dataObject.process(false).orElseThrow(() -> new Exception()));
}
@Test()
void givenEmptyList_whenFindFirst_getDefaultValue() {
assertTrue(dataObject.findFirst().equalsIgnoreCase(UsingOptional.DEFAULT_VALUE));
}
@Test()
void givenEmptyList_whenFindOptionalFirst_returnsEmptyOptional() {
assertFalse(dataObject.findOptionalFirst().isPresent());
}
@Test()
void whenOptionalListFirst_returnsEmptyOptional() {
assertFalse(dataObject.optionalListFirst().isPresent());
}
}