Search code examples
javajava-8java-streamoption-type

How to Set an Object's Property using Streams


I am streaming and filtering values . Is there any way i can set another object value after the filter. I dont want to collect or return anything.

boolean b = ddlTables.stream()
    .filter(d -> d.getFieldName().equalsIgnoreCase("restrict"))
    .findFirst()
    .isPresent();

if (b) {
    validationModel.setFailMessage("Fail");
}

I don't want to do it in the way shown above.

I'm trying to avoid the return and if condition and set the value like below.

ddlTables.stream()
    .filter(d -> d.getFieldName().equalsIgnoreCase("restrict"))
    //  validationModel.setFailMessage("failed"); <- Need to set the object value 

Is there any way to achieve it?


Solution

  • Changing the state of objects outside the stream is discouraged by the Stream API documentation.

    But you can leverage the functionality provided by the Optional class.

    Method Optional.ifPresent() which allows providing an optional action in the form of Consumer that will be executed when result is present.

    It's also worth to extract the stream-statement into a separate method (nothing specific to streams - just the Single-responsibility principle).

    final Model validationModel = // something
    
    findByProperty(ddlTables, "restrict")
        .ifPresent(something -> validationModel.setFailMessage("Fail"));
    
    public static Optional<Something> findByProperty(List<Something> list, String targetValue) {
        return list.stream()
            .filter(d -> d.getFieldName().equalsIgnoreCase(targetValue))
            .findFirst();
    }
    

    A link to Online Demo