4

I have this piece of code:

boolean anyMatch = ifxStopChkInqRs.getBankSvcRs().stream().anyMatch(
  b -> b.getStopChkInqRs().stream().anyMatch(
    i -> i.getStopChkRec().stream()
      .filter(d -> d.getStopChkInfo().getDesc().equals("D"))
      .findFirst()
      .isPresent()));

This returns a true/false value correctly, and quits at the first object it finds if any.

But, how can I return the object itself, which in this case would be of type StopChkRec - the i object? I changed both anyMatch to peek and a added a get() in front of findFirst(), but that returned a stream at the highest level - Stream<BankSvcRs> - which beats the whole search purpose of course.

Any help and/or a re-approach to re-constructing this lambda expression is welcome.

mohsenmadi
  • 2,277
  • 1
  • 23
  • 34

2 Answers2

2

Here it is:

    Optional<StopChkRecType> findFirst = ifxStopChkInqRs.getBankSvcRs()
        .stream()
        .flatMap(b -> b.getStopChkInqRs().stream())
        .flatMap(i -> i.getStopChkRec().stream())
        .filter(d -> d.getStopChkInfo().getDesc().equals("D"))
        .findFirst();

Answer inspired by @ykaganovich who put me on the right track with flatMap, but also at this link which explains how to go deep and come out clean.

Community
  • 1
  • 1
mohsenmadi
  • 2,277
  • 1
  • 23
  • 34
1

Something like this? (untested)

ifxStopChkInqRs.getBankSvcRs().stream().flatMap(b -> b.getStopChkInqRs())
  .filter(i -> i != null)
  .flatMap(i -> i.getStopChkRec())
    .filter(d -> (d != null && d.getStopChkInfo().getDesc().equals("D")))
    .findFirst()

I don't know where you need to filter out nulls, and if you can use findAny() instead of findFirst()

ykaganovich
  • 14,736
  • 8
  • 59
  • 96
  • I tested your expression but it wouldn't even pass syntax validation. Nulls are okay, for I may be looking for what's not there. I thought Optional would help in this regard. Why the `flatMap`? I will read on it a little. – mohsenmadi Nov 15 '16 at 20:53