Codeninja
Codeninja

Reputation: 322

How to return value of optional after mapping in java 8

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

Upvotes: 1

Views: 756

Answers (2)

A.Casanova
A.Casanova

Reputation: 1017

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.

Upvotes: 0

Sweeper
Sweeper

Reputation: 271150

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

Upvotes: 4

Related Questions