is there a nice way to create a different List if stream is empty?
Here if special
is empty I want to create a new List
with another value.
But if special
is not empty I want to create List
based on special
.
I don't know is there a nice way to combine these with a stream
Here is a not so nice solution
class X {
public static void main(String[] args) {
String myString = "test";
List<String> special = getSpecialVals();
List<String> newVals =
special.isEmpty() ?
Arrays.asList(myString) :
special.stream().map(s ->
createNewVal(s)).collect(Collectors.toList());
}
static public List<String> getSpecialVals() {
// but can return empty list
return Arrays.asList("One", "Two");
}
static public String createNewVal(String origVal) {
return origVal.toUpperCase();
}
}
if you want to have it as a single pipeline then you could do:
List<String> strings =
Optional.of(special)
.filter(e -> !e.isEmpty())
.map(l -> l.stream().map(s -> createNewVal(s))
.collect(Collectors.toList()))
.orElseGet((() -> Collections.singletonList(myString)));
However, I wouldn't recommend proceeding with this approach simply because it's not the intended purpose of Optional.
instead, you would be better off with:
List<String> result;
if(special.isEmpty())
result = Collections.singletonList(myString);
else
result = special.stream().map(s -> createNewVal(s)).collect(Collectors.toList());
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