• @[email protected]
    link
    fedilink
    05 days ago

    I try to prefer .findAny() over .findFirst() because it will perform better in some cases (it will have to resolve whether they more are other matches and which one is actually first before they can terminate - more relevant for parallel streams I think) but otherwise I like the first. I’d probably go with some sort of composed predicate for the second, to be able to easily add new criteria. But I could be over engineering.

    I mostly just posted because I think not enough people are aware of the reasons to use findAny as a default unless findFirst is needed.

    • magic_lobster_party
      link
      fedilink
      05 days ago

      For me I have the habit of doing findFirst because determinism is important where I work. But I agree with you if determinism is not of importance.

      • @[email protected]
        link
        fedilink
        04 days ago

        I would only note that for the vast majority of my experience these streams can only return up to a single match. Determinism isn’t really preserved by findFirst, either, unless the sort order is set up that way.

        Finding the first Jim Jones in a table is no more reliable that finding any Jim Jones. But finding PersonId 13579 is deterministic whether you findFirst or findAny.

        Perhaps you work in a different domain where your experience is different.