I want to return a value of a stream based on a condition. Take the following as an example only, where I want to map any apple to Food.APPLE
:
public enum Food {
APPLE, APPLE2, APPLE3, BANANA, PINEAPPLE, CUCUMBER;
private static final Food[] APPLES = new Food[] {APPLE, APPLE2, APPLE3};
//java7
public Food fromValue(String value) {
for (Food type : Food.values()) {
if (type.name().equalsIgnoreCase(value)) {
return ArrayUtils.contains(APPLES, type) ? APPLE : type;
}
}
return null;
}
//java8: how to include the array check for APPLES?
public Food fromValue(String value) {
return Arrays.stream(Food.values()).
filter(type -> type.name().equalsIgnoreCase(value))
.findFirst()
.orElse(null);
}
}
How can I include the ternary condition in a stream?
You could do it like this:
import static java.util.AbstractMap.SimpleImmutableEntry;
...
enum Food {
APPLE, APPLE2, APPLE3, BANANA, PINEAPPLE, CUCUMBER;
private static final Map<String, Food> MAP = Stream.concat(
Stream.of(APPLE, APPLE2, APPLE3).map(e -> new SimpleImmutableEntry<>(e.name().toLowerCase(), APPLE)),
Stream.of(BANANA, PINEAPPLE, CUCUMBER).map(e -> new SimpleImmutableEntry<>(e.name().toLowerCase(), e)))
.collect(toMap(SimpleImmutableEntry::getKey, SimpleImmutableEntry::getValue));
public static Food fromValue(String value) {
return MAP.get(value.toLowerCase());
}
}
The lookup in the map will be O(1)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With