简体   繁体   中英

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 ", "(", ")"));
}

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 + ")";
    })

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 ", "(", ")"));
}

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 () .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM