add operation to extract the only element from a stream

XMLWordPrintable

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

      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()).

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

              Created:
              Updated: