1

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();
}

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.