• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

165
Views
Creating an Object from Optional<Object>

So I've created a stream which comes from a List but I'm having some trouble converting it into a <ObjectType>, here's what I've tried:

ObjectType sco = getList().stream()
                          .filter(p -> p.getValue() == value)
                          .findFirst(); //also tried .orElse(null);

would anyone, please, be so kind as to suggest where I'm going wrong? (I apologize if this has been asked before but I couldn't find a discussion on this particular topic (or didn't know the proper terms to search for))

Thanks in advance!

about 3 years ago · Santiago Trujillo
2 answers
Answer question

0

findFirst() gives you an Optional and you then have to decide what to do if it's not present. So findFirst().orElse(null) should give you the object or null if it's not present

You could just do a .get() on the Optional, but that could be regarded as poor practice since get() will throw an exception if Optional has no content. You should normally assert presence/absence of the Optional and decide what to do in each case (that's why it's there - so that you know something is truly optional and you have to determine what to do)

If you have an action you want to perform on object presence, and you don't want to do anything on absence, you can call .ifPresent() and provide a lambda as an argument. That will be called with the contained object, if present.

As of Java 9, a further solution would be to use Optional.ifPresentOrElse()

about 3 years ago · Santiago Trujillo Report

0

I think you may be looking for findFirst().or Else(null). findFirst() will return an Optional - empty in the case of an empty steam.

Unless I misunderstood your comment. Have you tried this, or did you try orElse(null) without findFirst()?

about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error