Last active
January 17, 2023 14:29
-
-
Save stefanofago73/dc30bb839d89d31efaf5710bc452d5dd to your computer and use it in GitHub Desktop.
A study on extracting a list of values from a list of Optionals: What implementation? And why?
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 static java.util.stream.Collectors.toList; | |
import java.util.List; | |
import java.util.Optional; | |
import java.util.function.Function; | |
/** | |
* | |
* @author Stefano Fago | |
* | |
*/ | |
public class IceCreamFactory { | |
record IceCream(String color,String taste){} | |
public static final Optional<IceCream> parse(String data) | |
{ | |
String [] maybePair = data.split(";"); | |
return maybePair.length==2? | |
Optional.of(new IceCream(maybePair[0], maybePair[1])): | |
Optional.empty(); | |
} | |
// | |
// | |
// This implementation is more "imperative"... | |
// | |
// | |
public static List<IceCream> produce_version_1(List<String> data) | |
{ | |
return data.stream() | |
.map(IceCreamFactory::parse) | |
.filter(Optional::isPresent) | |
.map(Optional::get) | |
.collect(toList()); | |
} | |
// | |
// | |
// This implementation is more "functional"... also if Optional costruct | |
// can be considered "not so friendly"... but there's enough to operate... | |
// Using flatMap make possible a better transformation... | |
// | |
// | |
public static List<IceCream> produce_version_2(List<String> data) | |
{ | |
return data.stream() | |
.map(IceCreamFactory::parse) | |
.flatMap(Optional::stream) | |
.collect(toList()); | |
} | |
// | |
// | |
// This implementation make the compromise to introduce the | |
// concept of "default fallback" to avoid using flatMap but | |
// isn't always possible... | |
// | |
public static List<IceCream> produce_version_3(List<String> data) | |
{ | |
return data.stream() | |
.map(IceCreamFactory::parse) | |
.map(maybe->maybe.orElse(new IceCream("Invalid", "Invalid"))) | |
.collect(toList()); | |
} | |
public static void main(String[] args) { | |
var icecreamsData = List.of("yellow;banana", | |
"red;strawberry", | |
"bluesmurf"); | |
List<Function<List<String>,List<IceCream>>> operations = | |
List.of(IceCreamFactory::produce_version_1, | |
IceCreamFactory::produce_version_2, | |
IceCreamFactory::produce_version_3); | |
operations.stream() | |
.map(operation->operation.apply(icecreamsData)) | |
.forEach(System.out::println); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment