Class MoreCollectors


  • @GwtCompatible
    public final class MoreCollectors
    extends java.lang.Object
    Collectors not present in java.util.stream.Collectors that are not otherwise associated with a com.google.common type.
    Since:
    21.0
    Author:
    Louis Wasserman
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static <T extends @Nullable java.lang.Object>
      java.util.stream.Collector<T,​?,​T>
      onlyElement()
      A collector that takes a stream containing exactly one element and returns that element.
      static <T> java.util.stream.Collector<T,​?,​java.util.Optional<T>> toOptional()
      A collector that converts a stream of zero or one elements to an Optional.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Method Detail

      • toOptional

        public static <T> java.util.stream.Collector<T,​?,​java.util.Optional<T>> toOptional()
        A collector that converts a stream of zero or one elements to an Optional.
        Returns:
        Optional.of(onlyElement) if the stream has exactly one element (must not be null) and returns Optional.empty() if it has none.
        Throws:
        java.lang.IllegalArgumentException - if the stream consists of two or more elements.
        java.lang.NullPointerException - if any element in the stream is null.
      • onlyElement

        public static <T extends @Nullable java.lang.Object> java.util.stream.Collector<T,​?,​T> onlyElement()
        A collector that takes a stream containing exactly one element and returns that element. The returned collector throws an IllegalArgumentException if the stream consists of two or more elements, and a NoSuchElementException if the stream is empty.