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

add operation to extract the only element from a stream

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Unresolved
    • Icon: P4 P4
    • None
    • None
    • 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()).

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

              Created:
              Updated: