wesvin
wesvin

Reputation: 45

Set value to a string variable, from an object based on the condition using Java Streams

I am new to Java streams. I have a code snippet that i need to write using java streams. I am trying to set a value to a string based on a condition. I tried to look for solutions and experimented by using anyMatch, however could not get anywhere.

String loadAGENTID = "";
for(ReportGenerationParameter rgp : loadReportTableExt.getReportGenerationParameters()) {
    if (rgp.getKey().equalsIgnoreCase(RapFilter.IDUSR)) {
        loadAGENT_ID = rgp.getValue();
    }
}

String loadAGENTID is to be used in the code. Any suggestion is welcome. Thank you.

I have tried using Arrays.stream and anyMatch but no luck so far

boolean todoName =
        Arrays.stream(loadReportTableExt.getReportGenerationParameters())
              .anyMatch(item -> item.getKey().equalsIgnoreCase(RapFilter.IDUSR));

if (todoName) {
    // want to set the value of the respective object.
    loadAGENT_ID = item.getValue();
}

Upvotes: 1

Views: 543

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 40058

Use the filter to find the matching object and then use findFirst which returns the first matching element

String loadAGENTID  = loadReportTableExt.getReportGenerationParameters()
                                        .stream()
                                        .filter(rgp-> rgp.getKey().equalsIgnoreCase(RapFilter.IDUSR))
                                        .findFirst()
                                        .map(rgp->rgp.getValue())   // returns value from first matching element 
                                        .orElse("");  // none of them matched returns default value

Upvotes: 2

Related Questions