Search code examples
javajava-stream

Return enum object using validate method inside list validate function


I have a problem that I want to resolve with Java streams if possible. This is my code.

class Foo {
    private String name;
    private String surname;
    // getters and setters
}

enum FooError {
    NO_NAME("Name cannot be null."), NO_SURNAME("Surname cannot be null");

    private final String message;

    FooError(final String message) {
        this.message = message;
    }

    public String message() {
        return message;
    }

}

public FooError validate(final Foo foo) {
    if (StringUtils.isBlank(foo.getName())) {
        return FooError.NO_NAME;
    }

    if (StringUtils.isBlank(foo.getSurname())) {
        return FooError.NO_SURNAME;
    }
    return null;
}

public FooError validateFooList(final List<Foo> fooList) {
    FooError = fooList.stream()....
}

I want to return the first FooError ocurrence or null in the list using streams. Is it possible and if so, how can I do it?


Solution

  • public FooError validateFooList(final List<Foo> fooList) {
        return fooList.stream()
                .map(this::validate)
                .filter(Objects::nonNull)
                .findFirst()
                .orElse(null);
        }
    

    This calls the validate method for each Foo instance and filters only the non-null FooError values, finds and returns the first FooError in the stream or null if there are none.