How to return object instead of stream using peek

2019-07-15 02:42发布

问题:

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.

回答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()



回答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.



标签: java lambda