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:
+30
-3
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user