Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Java 8 stream from a nullable list

Is there a way to check the null in java8, if list is null return null, else do the operations.

 public Builder withColors(List<String> colors) {
        this.colors= colors== null ? null :
                colors.stream()
                .filter(Objects::nonNull)
                .map(color-> Color.valueOf(color))
                .collect(Collectors.toList());

        return this;
    }

I see there is an option to use

Optional.ofNullable(list).map(List::stream) 

but in this way I get error code on Color.valueOf(color)

Thanks

like image 436
userit1985 Avatar asked Mar 06 '23 22:03

userit1985


2 Answers

Optional.ofNullable(list).map(List::stream) would give you a Optional<Stream<String>>, which you can't call filter on.

You can put the entire Stream processing inside the Optional's map():

public Builder withColors(List<String> colors) {
    this.colors = Optional.ofNullable(colors).map(
        list -> list.stream()
                    .filter(Objects::nonNull)
                    .map(color-> Color.valueOf(color))
                    .collect(Collectors.toList()))
                    .orElse(null);
    return this;
}
like image 86
Eran Avatar answered Mar 15 '23 08:03

Eran


There are a couple of things that may be you should re-think.

First of all may be passing a Set<String> colors instead of a List would make more sense, since it seems that Color is an enum to begin with. Then, may be it would make more sense to check against equalsIgnoreCase, so that red or RED would still produce an enum instance. Also an if statement is probably much more clear to check for a possibly null input. And last streaming in the opposite direction - from the enum would make more sense (also avoiding the null check) I have not implemented the recommendations above, just for simplicity.

public Builder withColors(List<String> colors) {
    if(colors == null){
        this.colors = Collection.emptyList();
    }

    this.colors = EnumSet.allOf(Color.class)
            .stream()
            .filter(x -> colors.stream().anyMatch(y -> x.toString().equals(y)))
            .collect(Collectors.toList());
    return this;
}
like image 25
Eugene Avatar answered Mar 15 '23 08:03

Eugene