Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a different List if Stream is empty

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();
    }
}
like image 855
VextoR Avatar asked Dec 18 '22 19:12

VextoR


1 Answers

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());
  • The latter is definitely more readable hence causes less work for the brain in trying to figure out what's happening. ;)
  • The latter also avoids creating an Optional instance leading to better efficiency
like image 110
Ousmane D. Avatar answered Dec 30 '22 21:12

Ousmane D.