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
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;
}
                        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;
}
                        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