Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8201273

add operation to extract the only element from a stream

    XMLWordPrintable

    Details

    • Type: Enhancement
    • Status: Open
    • Priority: P4
    • Resolution: Unresolved
    • Affects Version/s: None
    • Fix Version/s: None
    • Component/s: core-libs
    • Labels:

      Description

      There are cases where the result of a stream should have *exactly* one element. The findAny() operation will get the element, but this loses two ways: 1) it returns an optional which *should* have a value always present, so one has to do a getOrThrow(); 2) if there is more than one element, this fact is lost.

      An alternative would be

          List<T> list = stream.<operation>.<operation>. ...
              .limit(2)
              .collect(toList());
          assert list.size() == 1;
          T result = list.get(0);

      This is fairly cumbersome.

      This function could be expressed as a terminal operation, e.g. stream.findOnly(), or it could be expressed as a collector, e.g. stream.collect(onlyElement()).

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                smarks Stuart Marks
                Reporter:
                smarks Stuart Marks
              • Votes:
                0 Vote for this issue
                Watchers:
                1 Start watching this issue

                Dates

                • Created:
                  Updated: