Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return false for an empty list if using Stream.allMatch()?

I want to use one statement with Java streams.

I want to filter all Servicework Objects, where the requirements are "true" and then check if all Servicework objects has the Status "Done".

But if the serviceworkList ist empty, then variable "validate" is false. I know the specification of allMatch, that if list is empty, then the return is true.

Any suggestions on how I could rebuild the stream, that if list ist empty i would get false ?

public class Service{

    List<ServiceWork> serviceWorkList = new ArrayList<>();


    boolean validate = serviceWorkList
        .stream()
        .filter(ServiceWork::isRequirement)
        .allMatch(a -> a.getStatus() == Status.DONE);

}

class ServiceWork {

    private Status status;
    private boolean isRequirement;

    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    public boolean isRequirement() {
        return isRequirement;
    }

    public void setRequirement(boolean requirement) {
        isRequirement = requirement;
    }
}

enum Status {
    DONE, NOT_DONE
}
like image 598
java java Avatar asked Dec 18 '22 18:12

java java


1 Answers

Just add an additional check that the list is not empty:

boolean validate = !serviceWorkList.isEmpty() && serviceWorkList
    .stream()
    .filter(ServiceWork::isRequirement)
    .allMatch(a -> a.getStatus() == Status.DONE);

After your comment, you can use this:

Set<Status> status = serviceWorkList
    .stream()
    .filter(ServiceWork::isRequirement)
    .map(ServiceWork::getStatus())
    .collect(Collectors.toCollection(() -> EnumSet.noneOf(Status.class)));

boolean validate = status.remove(Status.DONE) == Status.DONE && status.isEmpty();

It first collects all the status into an EnumSet, then removes Status.DONE from the set and if the set is empty, every element has getStatus() == Status.DONE.

This removes the short circuiting though, so it will still iterate over the serviceWorkerList even though a Status other than Status.DONE has been encountered

like image 85
Lino Avatar answered Feb 23 '23 12:02

Lino