alma elghoul
alma elghoul

Reputation: 203

How to return null when list is empty in Java 8?

How can I change this method so that it returns null if the list passed as a parameter is empty without using an if statement?

 default String getFiltersExpression(List<WorklistViewDto.Filter> filters) {
    return Optional.ofNullable(filters)
        .map(Collection::stream)
        .orElseGet(Stream::empty)
        .map(WorkListViewMapper::formatValue)
        .map(f -> f.getCriteria() + f.getOperator() + f.getValue())
        .collect(Collectors.joining(" AND ", "(", ")"));
}

Upvotes: 5

Views: 11246

Answers (3)

Benoit
Benoit

Reputation: 5394

An alternative way is to start streaming only if the list is non null and non empty:

default String getFiltersExpression(List<WorklistViewDto.Filter> filters) {
    return Optional.ofNullable(filters)
            .filter(fs -> !fs.isEmpty())
            .map(fs -> fs.stream()
                    .map(WorkListViewMapper::formatValue)
                    .map(f -> f.getCriteria() + f.getOperator() + f.getValue())
                    .collect(Collectors.joining(" AND ", "(", ")")))
            .orElse(null);
}

Then you get null instead of ().

Upvotes: 1

Naman
Naman

Reputation: 31878

I would recommend not returning null and rather returning a "()" string as the filter expression for this you can just append a filter for an empty list there as :

String getFiltersExpression(List<Filter> filters) {
    return Optional.ofNullable(filters)
            .filter(l -> !l.isEmpty())
            .map(Collection::stream)
            .orElseGet(Stream::empty)
            .map(WorkListViewMapper::formatValue)
            .map(f -> f.getCriteria() + f.getOperator())
            .collect(Collectors.joining(" AND ", "(", ")"));
}

Using Java-9 syntax :

String getFiltersExpressions(List<Filter> filters) {
    return Stream.ofNullable(filters)
            .flatMap(Collection::stream)
            .map(WorkListViewMapper::formatValue)
            .map(f -> f.getCriteria() + f.getOperator() + f.getValue())
            .collect(Collectors.joining(" AND ", "(", ")"));
}

Upvotes: 2

matt
matt

Reputation: 12347

You can do it with Collectors.collectingAndThen .

.collect( 
    Collectors.collectingAndThen(
        Collectors.joining(), 
        str->{
            if(str.isEmpty()) return null; 
            return str;
        }
     )
 );

Given OP's joining statement, Collectors.joining(" AND ", "(", ")") we could modify the above.

Collectors.collectingAndThen(
    Collectors.joining(" AND "), 
    str->{
            if(str.isEmpty()) return null; 
            return "(" + str + ")";
    })

Upvotes: 6

Related Questions