1

I need to get the String value which is the identifier, but this return void instead of string value. How can I return the string value?

    String previousReadyForHome = information.getPreviousContact().ifPresent(val->{
      Arrays.stream(val.basic.identifiers).filter(s -> s.type == readyForHomeType)
        .map(s -> s.identifier).findFirst().orElse(null);
    });
1
  • 2
    Dont do ifPresent. but .map or .flatMap on the given Optional. Commented Jan 19, 2021 at 12:04

2 Answers 2

4

You should not use ifPresent, as you have found out, it returns void. Rather, you should use flatMap, which gives you another Optional<String>, which you can then use orElse to unwrap it to null.

String previousReadyForHome = information.getPreviousContact().flatMap(val->
  Arrays.stream(val.basic.identifiers).filter(s -> s.type == readyForHomeType)
    .map(s -> s.identifier).findFirst()
).orElse(null);
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming your classes names:

Optional<String> previousReadyForHome = information.getPreviousContact()
    .map(Contact::getBasic)
    .map(BasicInfo::getIdentifiers)
    .flatMap(identifiers -> Arrays.stream(identifiers)
        .filter(identifier -> identifier.getType() == readyForHomeType)
        .map(Identifier::getIdentifier)
        .findFirst());

It is just a more readable approach.

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.