-1

I have one object which contains multiple list. So, I traversed using map. one object three list. Traversed using map and finally using find first. Is it possible to take single Optional instead of

Optional<Optional<Optional<String>>>

??

This is what I have tried

Optional<Optional<Optional<String>>> myString = myComplexObject.stream()
                                .map( obj1 -> obj1.getObj2().stream()
                                          .map( obj2 -> obj2.getObj3().stream() 
                                                    .filter(obj3 -> obj3.getMyString() .equalsIgnoreCase("Name")) 
                                                    .map(obj3 -> obj3.getMyString())
                                                    .findFirst()) 
                                          .findFirst())
                                .findFirst();

Kindly help

Bentaye
  • 9,403
  • 5
  • 32
  • 45
  • This is wat I m tryingOptional>> myString = myComplexObject .stream().map( obj1 -> obj1.getObj2() .stream().map( obj2 -> obj2.getObj3().stream() .filter(obj3 -> obj3.getMyString() .equalsIgnoreCase("Name")) .map(obj3 -> obj3.getMyString()).findFirst()) .findFirst()) .findFirst(); – Sabarish Dec 05 '19 at 13:16
  • 2
    @Sabarish include that in the question and make it readable. – f1sh Dec 05 '19 at 13:18
  • @Sabarish You can always as the person asking the question, edit it and improve for the others to read. – Naman Dec 05 '19 at 13:44
  • Have you tried `flatMap` instead of `map`? This way, you can map a stream without having the nested optionals. Nesting Optionals does not seem to make sense, IMHO. – Jochen Reinhardt Dec 10 '19 at 09:30

1 Answers1

1

Instead of map(), use flatMap():

myComplexObject.stream()
.flatMap(obj1 -> obj1.getObj2().stream()) // Stream of `obj2`
.flatMap(obj2 -> obj2.getObj3().stream()) // Stream of `obj3`
.map(obj3 -> obj3.getMyString())          // Stream of `string`
.filter(s -> s.equalsIgnoreCase("Name"))
.findFirst();             
Mạnh Quyết Nguyễn
  • 17,677
  • 1
  • 23
  • 51