Home > Software design >  How to Set an Object's Property using Streams
How to Set an Object's Property using Streams

Time:06-04

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?

CodePudding user response:

The only thing I can offer is this. It uses the result of the isPresent method to form a logical expression. But you must always return something from a stream or print a value using a terminal operation which triggers the flow of values. And let me reiterate that your first way of doing it was fine and that is exactly how I would do it.

if (ddlTables.stream().filter(d-> 
           d.getFieldName().equalsIgnoreCase("restrict")).findFirst().isPresent()) {
                            validationModel.setFailMessage("Fail");
}

CodePudding user response:

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

  • Related