Skip to content

Instantly share code, notes, and snippets.

@nipafx
Created May 27, 2020 07:49
Show Gist options
  • Save nipafx/9d598803ca24e11e83a7104ba081fbea to your computer and use it in GitHub Desktop.
Save nipafx/9d598803ca24e11e83a7104ba081fbea to your computer and use it in GitHub Desktop.
Optional vs null && Stream vs loop
package org.codefx.lab;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
class Lab {
// WITH OPTIONAL &
static List<Function<String, Optional<String>>> operatorsToOptional =
List.of(
s -> Optional.empty(),
s -> Optional.of(new StringBuilder(s).reverse().toString()));
// ... & stream
static Optional<String> streamOptional(String string) {
return operatorsToOptional.stream()
.flatMap(operator -> operator.apply(string).stream())
.findFirst();
}
// ... & loop
static Optional<String> loopOptional(String string) {
for (var operator : operatorsToOptional) {
var uri = operator.apply(string);
if (uri.isPresent())
return uri;
}
return Optional.empty();
}
// WITH NULL & ...
static Collection<UnaryOperator<String>> operatorsToNull =
List.of(
s -> null,
s -> new StringBuilder(s).reverse().toString());
// ... & stream
static String streamNull(String string) {
return operatorsToNull.stream()
.flatMap(operator -> Stream.ofNullable(operator.apply(string)))
.findFirst()
.orElse(null);
}
// ... & loop
static String loopNull(String string) {
for (var operator : operatorsToNull) {
var uri = operator.apply(string);
if (uri != null)
return uri;
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment