Class StreamEx<T>

Type Parameters:
T - the type of the stream elements
All Implemented Interfaces:
AutoCloseable, Iterable<T>, BaseStream<T,Stream<T>>, Stream<T>

public final class StreamEx<T> extends AbstractStreamEx<T,StreamEx<T>>
A Stream implementation with additional functionality.

While StreamEx implements Iterable, it is not a general-purpose Iterable as it supports only a single Iterator; invoking the iterator method to obtain a second or subsequent iterator throws IllegalStateException.

  • Constructor Details

  • Method Details

    • supply

      StreamEx<T> supply(Stream<T> stream)
      Specified by:
      supply in class AbstractStreamEx<T,StreamEx<T>>
    • supply

      StreamEx<T> supply(Spliterator<T> spliterator)
      Specified by:
      supply in class AbstractStreamEx<T,StreamEx<T>>
    • collapseInternal

      private <R> StreamEx<R> collapseInternal(BiPredicate<? super T,? super T> collapsible, Function<T,R> mapper, BiFunction<R,T,R> accumulator, BinaryOperator<R> combiner)
    • nonNull

      public StreamEx<T> nonNull()
      Description copied from class: AbstractStreamEx
      Returns a stream consisting of the elements of this stream that aren't null.

      This is an intermediate operation.

      Overrides:
      nonNull in class AbstractStreamEx<T,StreamEx<T>>
      Returns:
      the new stream
      See Also:
    • select

      public <TT> StreamEx<TT> select(Class<TT> clazz)
      Returns a stream consisting of the elements of this stream which are instances of given class.

      This is an intermediate operation.

      Type Parameters:
      TT - a type of instances to select.
      Parameters:
      clazz - a class which instances should be selected
      Returns:
      the new stream
    • filterBy

      public <K> StreamEx<T> filterBy(Function<? super T,? extends K> mapper, K value)
      Returns a stream consisting of the elements of this stream for which the supplied mapper function returns the given value.

      This is an intermediate operation.

      This method behaves like filter(t -> Objects.equals(value, mapper.apply(t))).

      Type Parameters:
      K - type of the value returned by mapper function.
      Parameters:
      mapper - a non-interfering , stateless function which is applied to the stream element and its returned value is compared with the supplied value.
      value - a value the mapper function must return to pass the filter.
      Returns:
      the new stream
      Since:
      0.6.4
      See Also:
    • removeBy

      public <K> StreamEx<T> removeBy(Function<? super T,? extends K> mapper, K value)
      Returns a stream consisting of the elements of this stream except those for which the supplied mapper function returns the given value.

      This is an intermediate operation.

      This method behaves like filter(t -> !Objects.equals(value, mapper.apply(t))).

      Type Parameters:
      K - type of the value returned by mapper function.
      Parameters:
      mapper - a non-interfering , stateless function which is applied to the stream element and its returned value is compared with the supplied value.
      value - a value the mapper function must not return to pass the filter.
      Returns:
      the new stream
      Since:
      0.6.4
      See Also:
    • mapToEntry

      public <V> EntryStream<T,V> mapToEntry(Function<? super T,? extends V> valueMapper)
      Returns an EntryStream consisting of the Map.Entry objects which keys are elements of this stream and values are results of applying the given function to the elements of this stream.

      This is an intermediate operation.

      Type Parameters:
      V - The Entry value type
      Parameters:
      valueMapper - a non-interfering, stateless function to apply to each element
      Returns:
      the new stream
    • mapToEntry

      public <K, V> EntryStream<K,V> mapToEntry(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valueMapper)
      Returns an EntryStream consisting of the Map.Entry objects which keys and values are results of applying the given functions to the elements of this stream.

      This is an intermediate operation.

      Type Parameters:
      K - The Entry key type
      V - The Entry value type
      Parameters:
      keyMapper - a non-interfering, stateless function to apply to each element
      valueMapper - a non-interfering, stateless function to apply to each element
      Returns:
      the new stream
    • mapFirst

      public StreamEx<T> mapFirst(Function<? super T,? extends T> mapper)
      Returns a stream where the first element is the replaced with the result of applying the given function while the other elements are left intact.

      This is a quasi-intermediate operation with tail-stream optimization.

      Parameters:
      mapper - a non-interfering , stateless function to apply to the first element
      Returns:
      the new stream
      Since:
      0.4.1
    • mapFirstOrElse

      public <R> StreamEx<R> mapFirstOrElse(Function<? super T,? extends R> firstMapper, Function<? super T,? extends R> notFirstMapper)
      Returns a stream where the first element is transformed using firstMapper function and other elements are transformed using notFirstMapper function.

      This is a quasi-intermediate operation.

      Type Parameters:
      R - The element type of the new stream element
      Parameters:
      firstMapper - a non-interfering , stateless function to apply to the first element
      notFirstMapper - a non-interfering , stateless function to apply to all elements except the first one.
      Returns:
      the new stream
      Since:
      0.6.0
      See Also:
    • mapLast

      public StreamEx<T> mapLast(Function<? super T,? extends T> mapper)
      Returns a stream where the last element is the replaced with the result of applying the given function while the other elements are left intact.

      This is a quasi-intermediate operation.

      The mapper function is called at most once. It could be not called at all if the stream is empty or there is short-circuiting operation downstream.

      Parameters:
      mapper - a non-interfering , stateless function to apply to the last element
      Returns:
      the new stream
      Since:
      0.4.1
    • mapLastOrElse

      public <R> StreamEx<R> mapLastOrElse(Function<? super T,? extends R> notLastMapper, Function<? super T,? extends R> lastMapper)
      Returns a stream where the last element is transformed using lastMapper function and other elements are transformed using notLastMapper function.

      This is a quasi-intermediate operation.

      Type Parameters:
      R - The element type of the new stream element
      Parameters:
      notLastMapper - a non-interfering , stateless function to apply to all elements except the last one.
      lastMapper - a non-interfering , stateless function to apply to the last element
      Returns:
      the new stream
      Since:
      0.6.0
      See Also:
    • peekFirst

      public StreamEx<T> peekFirst(Consumer<? super T> action)
      Returns a stream consisting of the elements of this stream, additionally performing the provided action on the first stream element when it's consumed from the resulting stream.

      This is an intermediate operation.

      The action is called at most once. For parallel stream pipelines, it's not guaranteed in which thread it will be executed, so if it modifies shared state, it is responsible for providing the required synchronization.

      Note that the action might not be called at all if the first element is not consumed from the input (for example, if there's short-circuiting operation downstream which stopped the stream before the first element).

      This method exists mainly to support debugging.

      Parameters:
      action - a non-interfering action to perform on the first stream element as it is consumed from the stream
      Returns:
      the new stream
      Since:
      0.6.0
    • peekLast

      public StreamEx<T> peekLast(Consumer<? super T> action)
      Returns a stream consisting of the elements of this stream, additionally performing the provided action on the last stream element when it's consumed from the resulting stream.

      This is an intermediate operation.

      The action is called at most once. For parallel stream pipelines, it's not guaranteed in which thread it will be executed, so if it modifies shared state, it is responsible for providing the required synchronization.

      Note that the action might not be called at all if the last element is not consumed from the input (for example, if there's short-circuiting operation downstream).

      This method exists mainly to support debugging.

      Parameters:
      action - a non-interfering action to perform on the first stream element as it is consumed from the stream
      Returns:
      the new stream
      Since:
      0.6.0
    • flatMapToEntry

      public <K, V> EntryStream<K,V> flatMapToEntry(Function<? super T,? extends Map<K,V>> mapper)
      Creates a new EntryStream populated from entries of maps produced by supplied mapper function which is applied to the every element of this stream.

      This is an intermediate operation.

      Type Parameters:
      K - the type of Map keys.
      V - the type of Map values.
      Parameters:
      mapper - a non-interfering, stateless function to apply to each element which produces a Map of the entries corresponding to the single element of the current stream. The mapper function may return null or empty Map if no mapping should correspond to some element.
      Returns:
      the new EntryStream
    • cross

      public <V> EntryStream<T,V> cross(V... other)
      Performs a cross product of current stream with specified array of elements. As a result the EntryStream is created whose keys are elements of current stream and values are elements of the specified array.

      The resulting stream contains all the possible combinations of keys and values.

      For example, writing StreamEx.of(1, 2).cross("a", "b"), you will have an ordered stream of the following entries: [1, "a"], [1, "b"], [2, "a"], [2, "b"].

      This is an intermediate operation.

      Type Parameters:
      V - the type of array elements
      Parameters:
      other - the array to perform a cross product with
      Returns:
      the new EntryStream
      Throws:
      NullPointerException - if other is null
      Since:
      0.2.3
    • cross

      public <V> EntryStream<T,V> cross(Collection<? extends V> other)
      Performs a cross product of current stream with specified Collection of elements. As a result the EntryStream is created whose keys are elements of current stream and values are elements of the specified collection.

      The resulting stream contains all the possible combinations of keys and values.

      This is an intermediate operation.

      Type Parameters:
      V - the type of collection elements
      Parameters:
      other - the collection to perform a cross product with
      Returns:
      the new EntryStream
      Throws:
      NullPointerException - if other is null
      Since:
      0.2.3
    • cross

      public <V> EntryStream<T,V> cross(Function<? super T,? extends Stream<? extends V>> mapper)
      Creates a new EntryStream whose keys are elements of current stream and corresponding values are supplied by given function. Each mapped stream is closed after its contents have been placed into this stream. (If a mapped stream is null an empty stream is used, instead.)

      This is an intermediate operation.

      Type Parameters:
      V - the type of values.
      Parameters:
      mapper - a non-interfering, stateless function to apply to each element which produces a stream of the values corresponding to the single element of the current stream.
      Returns:
      the new EntryStream
      Since:
      0.2.3
    • groupingBy

      public <K> Map<K,List<T>> groupingBy(Function<? super T,? extends K> classifier)
      Returns a Map whose keys are the values resulting from applying the classification function to the input elements, and whose corresponding values are Lists containing the input elements which map to the associated key under the classification function.

      There are no guarantees on the type, mutability or serializability of the Map or List objects returned.

      This is a terminal operation.

      Type Parameters:
      K - the type of the keys
      Parameters:
      classifier - the classifier function mapping input elements to keys
      Returns:
      a Map containing the results of the group-by operation
      See Also:
    • groupingBy

      public <K, D> Map<K,D> groupingBy(Function<? super T,? extends K> classifier, Collector<? super T,?,D> downstream)
      Returns a Map whose keys are the values resulting from applying the classification function to the input elements, and whose corresponding values are the result of reduction of the input elements which map to the associated key under the classification function.

      There are no guarantees on the type, mutability or serializability of the Map objects returned.

      This is a terminal operation.

      Type Parameters:
      K - the type of the keys
      D - the result type of the downstream reduction
      Parameters:
      classifier - the classifier function mapping input elements to keys
      downstream - a Collector implementing the downstream reduction
      Returns:
      a Map containing the results of the group-by operation
      See Also:
    • groupingBy

      public <K, D, M extends Map<K, D>> M groupingBy(Function<? super T,? extends K> classifier, Supplier<M> mapFactory, Collector<? super T,?,D> downstream)
      Returns a Map whose keys are the values resulting from applying the classification function to the input elements, and whose corresponding values are the result of reduction of the input elements which map to the associated key under the classification function.

      The Map will be created using the provided factory function.

      This is a terminal operation.

      Type Parameters:
      K - the type of the keys
      D - the result type of the downstream reduction
      M - the type of the resulting Map
      Parameters:
      classifier - the classifier function mapping input elements to keys
      mapFactory - a function which, when called, produces a new empty Map of the desired type
      downstream - a Collector implementing the downstream reduction
      Returns:
      a Map containing the results of the group-by operation
      See Also:
    • groupingTo

      public <K, C extends Collection<T>> Map<K,C> groupingTo(Function<? super T,? extends K> classifier, Supplier<C> collectionFactory)
      Returns a Map whose keys are the values resulting from applying the classification function to the input elements, and whose corresponding values are the collections of the input elements which map to the associated key under the classification function.

      There are no guarantees on the type, mutability or serializability of the Map objects returned.

      This is a terminal operation.

      Type Parameters:
      K - the type of the keys
      C - the type of the collection used in resulting Map values
      Parameters:
      classifier - the classifier function mapping input elements to keys
      collectionFactory - a function which returns a new empty Collection which will be used to store the stream elements.
      Returns:
      a Map containing the results of the group-by operation
      Since:
      0.2.2
      See Also:
    • groupingTo

      public <K, C extends Collection<T>, M extends Map<K, C>> M groupingTo(Function<? super T,? extends K> classifier, Supplier<M> mapFactory, Supplier<C> collectionFactory)
      Returns a Map whose keys are the values resulting from applying the classification function to the input elements, and whose corresponding values are the collections of the input elements which map to the associated key under the classification function.

      The Map will be created using the provided factory function.

      This is a terminal operation.

      Type Parameters:
      K - the type of the keys
      C - the type of the collection used in resulting Map values
      M - the type of the resulting Map
      Parameters:
      classifier - the classifier function mapping input elements to keys
      mapFactory - a function which, when called, produces a new empty Map of the desired type
      collectionFactory - a function which returns a new empty Collection which will be used to store the stream elements.
      Returns:
      a Map containing the results of the group-by operation
      Since:
      0.2.2
      See Also:
    • partitioningBy

      public Map<Boolean,List<T>> partitioningBy(Predicate<? super T> predicate)
      Returns a Map<Boolean, List<T>> which contains two partitions of the input elements according to a Predicate.

      This is a terminal operation.

      There are no guarantees on the type, mutability, serializability, or thread-safety of the Map returned.

      Parameters:
      predicate - a predicate used for classifying input elements
      Returns:
      a Map<Boolean, List<T>> which Boolean.TRUE key is mapped to the list of the stream elements for which predicate is true and Boolean.FALSE key is mapped to the list of all other stream elements.
      Since:
      0.2.2
      See Also:
    • partitioningBy

      public <D> Map<Boolean,D> partitioningBy(Predicate<? super T> predicate, Collector<? super T,?,D> downstream)
      Returns a Map<Boolean, D> which contains two partitions of the input elements according to a Predicate, which are reduced according to the supplied Collector.

      This is a terminal operation. The operation may short-circuit if the downstream collector is short-circuiting.

      There are no guarantees on the type, mutability, serializability, or thread-safety of the Map returned.

      Type Parameters:
      D - the result type of the downstream reduction
      Parameters:
      predicate - a predicate used for classifying input elements
      downstream - a Collector implementing the downstream reduction
      Returns:
      a Map<Boolean, List<T>> which Boolean.TRUE key is mapped to the result of downstream Collector collecting the stream elements for which predicate is true and Boolean.FALSE key is mapped to the result of downstream Collector collecting the other stream elements.
      Since:
      0.2.2
      See Also:
    • partitioningTo

      public <C extends Collection<T>> Map<Boolean,C> partitioningTo(Predicate<? super T> predicate, Supplier<C> collectionFactory)
      Returns a Map<Boolean, C> which contains two partitions of the input elements according to a Predicate.

      This is a terminal operation.

      There are no guarantees on the type, mutability, serializability, or thread-safety of the Map returned.

      Type Parameters:
      C - the type of Collection used as returned Map values.
      Parameters:
      predicate - a predicate used for classifying input elements
      collectionFactory - a function which returns a new empty Collection which will be used to store the stream elements.
      Returns:
      a Map<Boolean, C> which Boolean.TRUE key is mapped to the collection of the stream elements for which predicate is true and Boolean.FALSE key is mapped to the collection of all other stream elements.
      Since:
      0.2.2
      See Also:
    • joining

      public String joining()
      Returns a String which is the concatenation of the results of calling String.valueOf(Object) on each element of this stream in encounter order.

      This is a terminal operation.

      Returns:
      the result of concatenation. For empty input stream empty String is returned.
    • joining

      public String joining(CharSequence delimiter)
      Returns a String which is the concatenation of the results of calling String.valueOf(Object) on each element of this stream, separated by the specified delimiter, in encounter order.

      This is a terminal operation.

      Parameters:
      delimiter - the delimiter to be used between each element
      Returns:
      the result of concatenation. For empty input stream empty String is returned.
    • joining

      public String joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
      Returns a String which is the concatenation of the results of calling String.valueOf(Object) on each element of this stream, separated by the specified delimiter, with the specified prefix and suffix in encounter order.

      This is a terminal operation.

      Parameters:
      delimiter - the delimiter to be used between each element
      prefix - the sequence of characters to be used at the beginning of the joined result
      suffix - the sequence of characters to be used at the end of the joined result
      Returns:
      the result of concatenation. For empty input stream prefix + suffix is returned.
    • toArray

      public <A> A[] toArray(Class<A> elementClass)
      Returns an array containing all the stream elements using the supplied element type class to allocate an array.

      This is a terminal operation.

      Type Parameters:
      A - the element type of the resulting array
      Parameters:
      elementClass - the type of array elements
      Returns:
      an array containing the elements in this stream
      Throws:
      ArrayStoreException - if the runtime type of the array returned from the array generator is not a supertype of the runtime type of every element in this stream
      Since:
      0.6.3
      See Also:
    • toArray

      public <A> A[] toArray(A[] emptyArray)
      Returns an array containing all the stream elements. If the stream happens to contain no elements, the supplied empty array is returned instead. Otherwise, the new array is allocated, whose element type is the same as the element type of supplied empty array.

      This is a terminal operation.

      This method is useful when the stream is expected to return empty arrays often, so the same instance of empty array (presumably declared in some static final field) can be reused.

      Type Parameters:
      A - the element type of the resulting array
      Parameters:
      emptyArray - an empty array of the resulting type
      Returns:
      an array containing the elements in this stream or the passed empty array if the stream is empty
      Throws:
      ArrayStoreException - if the runtime type of the array returned from the array generator is not a supertype of the runtime type of every element in this stream
      Since:
      0.6.3
      See Also:
    • toFlatCollection

      public <U, C extends Collection<U>> C toFlatCollection(Function<? super T,? extends Collection<U>> mapper, Supplier<C> supplier)
      Returns a collection created by provided supplier function which contains all the elements of the collections generated by provided mapper from each element of this stream.

      This is a terminal operation.

      This method is equivalent to flatCollection(mapper).toCollection(supplier), but may work faster.

      Type Parameters:
      U - the type of the elements of the resulting collection
      C - the type of the resulting collection
      Parameters:
      mapper - a non-interfering , stateless function to apply to each element which produces a Collection of new values
      supplier - a supplier for the resulting collection
      Returns:
      the new collection.
      Since:
      0.3.7
    • toFlatList

      public <U> List<U> toFlatList(Function<? super T,? extends Collection<U>> mapper)
      Returns a List which contains all the elements of the collections generated by provided mapper from each element of this stream. There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toFlatCollection(Function, Supplier).

      This is a terminal operation.

      This method is equivalent to flatCollection(mapper).toList(), but may work faster.

      Type Parameters:
      U - the type of the elements of the resulting collection
      Parameters:
      mapper - a non-interfering , stateless function to apply to each element which produces a Collection of new values
      Returns:
      the new list.
      Since:
      0.3.7
    • toMap

      public <V> Map<T,V> toMap(Function<? super T,? extends V> valMapper)
      Returns a Map whose keys are elements from this stream and values are the result of applying the provided mapping functions to the input elements.

      This is a terminal operation.

      Returned Map is guaranteed to be modifiable.

      For parallel stream the concurrent Map is created.

      Use valuesToMap(Function) if this stream contains values, instead of keys.

      Type Parameters:
      V - the output type of the value mapping function
      Parameters:
      valMapper - a mapping function to produce values
      Returns:
      a Map whose keys are elements from this stream and values are the result of applying mapping function to the input elements
      Throws:
      IllegalStateException - if this stream contains duplicate objects (according to Object.equals(Object))
      See Also:
    • toMap

      public <K, V> Map<K,V> toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valMapper)
      Returns a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

      This is a terminal operation.

      Returned Map is guaranteed to be modifiable.

      For parallel stream the concurrent Map is created.

      Type Parameters:
      K - the output type of the key mapping function
      V - the output type of the value mapping function
      Parameters:
      keyMapper - a mapping function to produce keys
      valMapper - a mapping function to produce values
      Returns:
      a Map whose keys and values are the result of applying mapping functions to the input elements
      Throws:
      IllegalStateException - if duplicate mapped key is found (according to Object.equals(Object))
      See Also:
    • toMap

      public <K, V> Map<K,V> toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valMapper, BinaryOperator<V> mergeFunction)
      Returns a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

      This is a terminal operation.

      If the mapped keys contains duplicates (according to Object.equals(Object)), the value mapping function is applied to each equal element, and the results are merged using the provided merging function.

      Returned Map is guaranteed to be modifiable.

      Type Parameters:
      K - the output type of the key mapping function
      V - the output type of the value mapping function
      Parameters:
      keyMapper - a mapping function to produce keys
      valMapper - a mapping function to produce values
      mergeFunction - a merge function, used to resolve collisions between values associated with the same key, as supplied to Map.merge(Object, Object, BiFunction)
      Returns:
      a Map whose keys are the result of applying a key mapping function to the input elements, and whose values are the result of applying a value mapping function to all input elements equal to the key and combining them using the merge function
      Since:
      0.1.0
      See Also:
    • valuesToMap

      public <K> Map<K,T> valuesToMap(Function<? super T,? extends K> keyMapper)
      Returns a Map whose values are elements from this stream and keys are the result of applying the provided mapping functions to the input elements.

      This is a terminal operation.

      Returned Map is guaranteed to be modifiable.

      For parallel stream the concurrent Map is created.

      Type Parameters:
      K - the output type of the key mapping function
      Parameters:
      keyMapper - a mapping function to produce keys
      Returns:
      a Map whose values are elements from this stream and keys are the result of applying mapping function to the input elements
      Throws:
      IllegalStateException - if this stream contains duplicate objects (according to Object.equals(Object))
      Since:
      0.8.0
      See Also:
    • into

      public <C extends Collection<? super T>> C into(C collection)
      Drains the stream content into the supplied collection.

      This is a terminal operation.

      The stream content is added into the collection using either Collection.add(Object) or Collection.addAll(Collection) method.

      Type Parameters:
      C - type of the resulting collection
      Parameters:
      collection - a mutable collection to add new elements into
      Returns:
      the supplied collection, updated from this stream
      Since:
      0.6.3
    • toSortedMap

      public <V> SortedMap<T,V> toSortedMap(Function<? super T,? extends V> valMapper)
      Returns a SortedMap whose keys are elements from this stream and values are the result of applying the provided mapping functions to the input elements.

      This is a terminal operation.

      If this stream contains duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed.

      For parallel stream the concurrent SortedMap is created.

      Returned SortedMap is guaranteed to be modifiable.

      Use valuesToSortedMap(Function) if this stream contains values, instead of keys.

      Type Parameters:
      V - the output type of the value mapping function
      Parameters:
      valMapper - a mapping function to produce values
      Returns:
      a SortedMap whose keys are elements from this stream and values are the result of applying mapping function to the input elements
      Since:
      0.1.0
      See Also:
    • toSortedMap

      public <K, V> SortedMap<K,V> toSortedMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valMapper)
      Returns a SortedMap whose keys and values are the result of applying the provided mapping functions to the input elements.

      This is a terminal operation.

      If the mapped keys contains duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed.

      For parallel stream the concurrent SortedMap is created.

      Returned SortedMap is guaranteed to be modifiable.

      Type Parameters:
      K - the output type of the key mapping function
      V - the output type of the value mapping function
      Parameters:
      keyMapper - a mapping function to produce keys
      valMapper - a mapping function to produce values
      Returns:
      a SortedMap whose keys and values are the result of applying mapping functions to the input elements
      Since:
      0.1.0
      See Also:
    • toSortedMap

      public <K, V> SortedMap<K,V> toSortedMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valMapper, BinaryOperator<V> mergeFunction)
      Returns a SortedMap whose keys and values are the result of applying the provided mapping functions to the input elements.

      This is a terminal operation.

      If the mapped keys contains duplicates (according to Object.equals(Object)), the value mapping function is applied to each equal element, and the results are merged using the provided merging function.

      Returned SortedMap is guaranteed to be modifiable.

      Type Parameters:
      K - the output type of the key mapping function
      V - the output type of the value mapping function
      Parameters:
      keyMapper - a mapping function to produce keys
      valMapper - a mapping function to produce values
      mergeFunction - a merge function, used to resolve collisions between values associated with the same key, as supplied to Map.merge(Object, Object, BiFunction)
      Returns:
      a SortedMap whose keys are the result of applying a key mapping function to the input elements, and whose values are the result of applying a value mapping function to all input elements equal to the key and combining them using the merge function
      Since:
      0.1.0
      See Also:
    • valuesToSortedMap

      public <K> SortedMap<K,T> valuesToSortedMap(Function<? super T,? extends K> keyMapper)
      Returns a SortedMap whose values are elements from this stream and keys are the result of applying the provided mapping functions to the input elements.

      This is a terminal operation.

      If the mapped keys contains duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed.

      Returned SortedMap is guaranteed to be modifiable.

      Type Parameters:
      K - the output type of the key mapping function
      Parameters:
      keyMapper - a mapping function to produce keys
      Returns:
      a Map whose values are elements from this stream and keys are the result of applying mapping function to the input elements
      Throws:
      IllegalStateException - if this stream contains duplicate objects (according to Object.equals(Object))
      Since:
      0.8.0
      See Also:
    • toNavigableMap

      public <V> NavigableMap<T,V> toNavigableMap(Function<? super T,? extends V> valMapper)
      Returns a NavigableMap whose keys are elements from this stream and values are the result of applying the provided mapping functions to the input elements.

      This is a terminal operation.

      If this stream contains duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed.

      For parallel stream the concurrent NavigableMap is created.

      Returned NavigableMap is guaranteed to be modifiable.

      Use valuesToNavigableMap(Function) if this stream contains values, instead of keys.

      Type Parameters:
      V - the output type of the value mapping function
      Parameters:
      valMapper - a mapping function to produce values
      Returns:
      a NavigableMap whose keys are elements from this stream and values are the result of applying mapping function to the input elements
      Since:
      0.6.5
      See Also:
    • toNavigableMap

      public <K, V> NavigableMap<K,V> toNavigableMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valMapper)
      Returns a NavigableMap whose keys and values are the result of applying the provided mapping functions to the input elements.

      This is a terminal operation.

      If the mapped keys contains duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed.

      For parallel stream the concurrent NavigableMap is created.

      Returned NavigableMap is guaranteed to be modifiable.

      Type Parameters:
      K - the output type of the key mapping function
      V - the output type of the value mapping function
      Parameters:
      keyMapper - a mapping function to produce keys
      valMapper - a mapping function to produce values
      Returns:
      a NavigableMap whose keys and values are the result of applying mapping functions to the input elements
      Since:
      0.6.5
      See Also:
    • toNavigableMap

      public <K, V> NavigableMap<K,V> toNavigableMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valMapper, BinaryOperator<V> mergeFunction)
      Returns a NavigableMap whose keys and values are the result of applying the provided mapping functions to the input elements.

      This is a terminal operation.

      If the mapped keys contains duplicates (according to Object.equals(Object)), the value mapping function is applied to each equal element, and the results are merged using the provided merging function.

      Returned NavigableMap is guaranteed to be modifiable.

      Type Parameters:
      K - the output type of the key mapping function
      V - the output type of the value mapping function
      Parameters:
      keyMapper - a mapping function to produce keys
      valMapper - a mapping function to produce values
      mergeFunction - a merge function, used to resolve collisions between values associated with the same key, as supplied to Map.merge(Object, Object, BiFunction)
      Returns:
      a NavigableMap whose keys are the result of applying a key mapping function to the input elements, and whose values are the result of applying a value mapping function to all input elements equal to the key and combining them using the merge function
      Since:
      0.6.5
      See Also:
    • valuesToNavigableMap

      public <K> NavigableMap<K,T> valuesToNavigableMap(Function<? super T,? extends K> keyMapper)
      Returns a NavigableMap whose values are elements from this stream and keys are the result of applying the provided mapping functions to the input elements.

      This is a terminal operation.

      If the mapped keys contains duplicates (according to Object.equals(Object)), the value mapping function is applied to each equal element, and the results are merged using the provided merging function.

      Returned NavigableMap is guaranteed to be modifiable.

      Type Parameters:
      K - the output type of the key mapping function
      Parameters:
      keyMapper - a mapping function to produce keys
      Returns:
      a Map whose values are elements from this stream and keys are the result of applying mapping function to the input elements
      Throws:
      IllegalStateException - if this stream contains duplicate objects (according to Object.equals(Object))
      Since:
      0.8.0
      See Also:
    • append

      @SafeVarargs public final StreamEx<T> append(T... values)
      Returns a new StreamEx which is a concatenation of this stream and the supplied values.

      This is a quasi-intermediate operation.

      May return this if no values are supplied.

      Parameters:
      values - the values to append to the stream
      Returns:
      the new stream
    • append

      public StreamEx<T> append(T value)
      Returns a new StreamEx which is a concatenation of this stream and the supplied value.

      This is a quasi-intermediate operation with tail-stream optimization.

      Parameters:
      value - the value to append to the stream
      Returns:
      the new stream
      Since:
      0.5.4
    • append

      public StreamEx<T> append(Collection<? extends T> collection)
      Returns a new StreamEx which is a concatenation of this stream and the stream created from supplied collection.

      This is a quasi-intermediate operation.

      May return this if the supplied collection is empty and non-concurrent.

      Parameters:
      collection - the collection to append to the stream
      Returns:
      the new stream
      Since:
      0.2.1
    • prepend

      @SafeVarargs public final StreamEx<T> prepend(T... values)
      Returns a new StreamEx which is a concatenation of supplied values and this stream.

      This is a quasi-intermediate operation with tail-stream optimization.

      May return this if no values are supplied.

      Parameters:
      values - the values to prepend to the stream
      Returns:
      the new stream
    • prepend

      public StreamEx<T> prepend(T value)
      Returns a new StreamEx which is a concatenation of supplied value and this stream.

      This is a quasi-intermediate operation with tail-stream optimization.

      Parameters:
      value - the value to prepend to the stream
      Returns:
      the new stream
      Since:
      0.5.4
    • prepend

      public StreamEx<T> prepend(Collection<? extends T> collection)
      Returns a new StreamEx which is a concatenation of the stream created from supplied collection and this stream.

      This is a quasi-intermediate operation with tail-stream optimization.

      May return this if the supplied collection is empty and non-concurrent.

      Parameters:
      collection - the collection to prepend to the stream
      Returns:
      the new stream
      Since:
      0.2.1
    • ifEmpty

      @SafeVarargs public final StreamEx<T> ifEmpty(T... values)
      Returns a stream whose content is the same as this stream, except the case when this stream is empty. In this case, its contents is replaced with supplied values.

      This is a quasi-intermediate operation.

      Parameters:
      values - values to replace the contents of this stream if this stream is empty.
      Returns:
      the stream whose content is replaced by supplied values only if this stream is empty.
      Since:
      0.6.6
    • has

      public boolean has(T value)
      Returns true if this stream contains the specified value.

      This is a short-circuiting terminal operation.

      Parameters:
      value - the value to look for in the stream. If the value is null then the method will return true if this stream contains at least one null. Otherwise value.equals() will be called to compare stream elements with the value.
      Returns:
      true if this stream contains the specified value
      See Also:
    • without

      public StreamEx<T> without(T value)
      Returns a stream consisting of the elements of this stream that don't equal to the given value.

      This is an intermediate operation.

      Parameters:
      value - the value to remove from the stream. If the value is null then all nulls will be removed (like nonNull() works). Otherwise value.equals() will be used to test stream values and matching elements will be removed.
      Returns:
      the new stream
      Since:
      0.2.2
      See Also:
    • without

      @SafeVarargs public final StreamEx<T> without(T... values)
      Returns a stream consisting of the elements of this stream that don't equal to any of the supplied values.

      This is an intermediate operation. May return itself if no values were supplied.

      Current implementation scans the supplied values linearly for every stream element. If you have many values, consider using more efficient alternative instead. For example, remove(StreamEx.of(values).toSet()::contains).

      Future implementations may take advantage on using hashCode() or compareTo for Comparable objects to improve the performance.

      If the values array is changed between calling this method and finishing the stream traversal, then the result of the stream traversal is undefined: changes may or may not be taken into account.

      Parameters:
      values - the values to remove from the stream.
      Returns:
      the new stream
      Since:
      0.5.5
      See Also:
    • reverseSorted

      public StreamEx<T> reverseSorted()
      Returns a StreamEx consisting of the elements of this stream, sorted according to reverse natural order. If the elements of this stream are not Comparable, a ClassCastException may be thrown when the terminal operation is executed.

      For ordered streams, the sort is stable. For unordered streams, no stability guarantees are made.

      This is a stateful intermediate operation.

      Returns:
      the new stream
      Since:
      0.2.0
    • forPairs

      public void forPairs(BiConsumer<? super T,? super T> action)
      Performs an action for each adjacent pair of elements of this stream.

      This is a terminal operation.

      The behavior of this operation is explicitly non-deterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism. For any given element, the action may be performed at whatever time and in whatever thread the library chooses. If the action accesses shared state, it is responsible for providing the required synchronization.

      Parameters:
      action - a non-interfering action to perform on the elements
      Since:
      0.2.2
    • collapse

      public StreamEx<T> collapse(BiPredicate<? super T,? super T> collapsible, BinaryOperator<T> merger)
      Merge series of adjacent elements which satisfy the given predicate using the merger function and return a new stream.

      This is a quasi-intermediate partial reduction operation.

      This operation is equivalent to collapse(collapsible, Collectors.reducing(merger)).map(Optional::get) , but more efficient.

      Parameters:
      collapsible - a non-interfering, stateless predicate to apply to the pair of adjacent elements of the input stream which returns true for elements which are collapsible.
      merger - a non-interfering, stateless, associative function to merge two adjacent elements for which collapsible predicate returned true. Note that it can be applied to the results if previous merges.
      Returns:
      the new stream
      Since:
      0.3.1
    • collapse

      public <R, A> StreamEx<R> collapse(BiPredicate<? super T,? super T> collapsible, Collector<? super T,A,R> collector)
      Perform a partial mutable reduction using the supplied Collector on a series of adjacent elements.

      This is a quasi-intermediate partial reduction operation.

      Type Parameters:
      R - the type of the elements in the resulting stream
      A - the intermediate accumulation type of the Collector
      Parameters:
      collapsible - a non-interfering, stateless predicate to apply to the pair of adjacent elements of the input stream which returns true for elements which should be collected together.
      collector - a Collector which is used to combine the adjacent elements.
      Returns:
      the new stream
      Since:
      0.3.6
    • collapse

      public StreamEx<T> collapse(BiPredicate<? super T,? super T> collapsible)
      Returns a stream consisting of elements of this stream where every series of elements matched the predicate is replaced with first element from the series.

      This is a quasi-intermediate partial reduction operation.

      This operation is equivalent to collapse(collapsible, MoreCollectors.first()).map(Optional::get) , but more efficient.

      Note that this operation always tests the adjacent pairs of input elements. In some scenarios it's desired to test every element with the first element of the current series. In this case, consider using MoreCollectors.dominators(BiPredicate) collector instead.

      For sorted stream collapse(Objects::equals) is equivalent to distinct().

      Parameters:
      collapsible - a non-interfering, stateless predicate to apply to the pair of adjacent input elements which returns true for elements which are collapsible.
      Returns:
      the new stream
      Since:
      0.3.1
      See Also:
    • runLengths

      public EntryStream<T,Long> runLengths()
      Collapses adjacent equal elements and returns an EntryStream where keys are input elements and values specify how many elements were collapsed.

      This is a quasi-intermediate partial reduction operation.

      For sorted input runLengths().toMap() is the same as groupingBy(Function.identity(), Collectors.counting()), but may perform faster. For unsorted input the resulting stream may contain repeating keys.

      Returns:
      the new stream
      Since:
      0.3.3
    • groupRuns

      public StreamEx<List<T>> groupRuns(BiPredicate<? super T,? super T> sameGroup)
      Returns a stream consisting of lists of elements of this stream where adjacent elements are grouped according to supplied predicate.

      This is a quasi-intermediate partial reduction operation.

      There are no guarantees on the type, mutability, serializability, or thread-safety of the List objects of the resulting stream.

      This operation is equivalent to collapse(sameGroup, Collectors.toList()), but more efficient.

      Parameters:
      sameGroup - a non-interfering, stateless predicate to apply to the pair of adjacent elements which returns true for elements which belong to the same group.
      Returns:
      the new stream
      Since:
      0.3.1
    • intervalMap

      public <U> StreamEx<U> intervalMap(BiPredicate<? super T,? super T> sameInterval, BiFunction<? super T,? super T,? extends U> mapper)
      Returns a stream consisting of results of applying the given function to the intervals created from the source elements.

      This is a quasi-intermediate partial reduction operation. This operation is the same as groupRuns(sameInterval).map(list -> mapper.apply(list.get(0), list.get(list.size()-1))) , but has less overhead as only first and last elements of each interval are tracked.

      Type Parameters:
      U - the type of the resulting elements
      Parameters:
      sameInterval - a non-interfering, stateless predicate to apply to the pair of adjacent elements which returns true for elements which belong to the same interval.
      mapper - a non-interfering, stateless function to apply to the interval borders and produce the resulting element. If value was not merged to the interval, then mapper will receive the same value twice, otherwise it will receive the leftmost and the rightmost values which were merged to the interval. Intermediate interval elements are not available to the mapper. If they are important, consider using groupRuns(BiPredicate) and map afterwards.
      Returns:
      the new stream
      Since:
      0.3.3
      See Also:
    • withFirst

      public <R> StreamEx<R> withFirst(BiFunction<? super T,? super T,? extends R> mapper)
      Returns a stream consisting of the results of applying the given function to the first element and every single element of this stream. When the mapper is called for the first element of the resulting stream, both its arguments are the same and equal to the first element of this stream.

      This is a quasi-intermediate operation.

      The size of the resulting stream is exactly the same as the size of the input stream.

      Type Parameters:
      R - The element type of the new stream
      Parameters:
      mapper - a non-interfering, stateless function to apply to the first stream element and every other element
      Returns:
      the new stream
      Since:
      0.5.3
      See Also:
    • withFirst

      public EntryStream<T,T> withFirst()
      Creates an EntryStream consisting of the Map.Entry objects which keys are all the same and equal to the first element of this stream and values are the original elements of this stream. The first element of the resulting stream has the same key and value.

      This is a quasi-intermediate operation.

      The size of the resulting stream is exactly the same as the size of the input stream.

      Returns:
      the new stream
      Since:
      0.5.3
      See Also:
    • zipWith

      public <V, R> StreamEx<R> zipWith(Stream<V> other, BiFunction<? super T,? super V,? extends R> mapper)
      Creates a new StreamEx which is the result of applying of the mapper BiFunction to the corresponding elements of this stream and the supplied other stream. The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel. When the resulting stream is closed, the close handlers for both input streams are invoked.

      This is a quasi-intermediate operation.

      The resulting stream finishes when either of the input streams finish: the rest of the longer stream is discarded. It's unspecified whether the rest elements of the longer stream are actually consumed.

      The stream created by this operation may have poor characteristics and parallelize badly, so it should be used only when there's no other choice. If both input streams are random-access lists or arrays, consider using zip(List, List, BiFunction) or zip(Object[], Object[], BiFunction) respectively. If you want to zip the stream with the stream of indices, consider using EntryStream.of(List) instead.

      Type Parameters:
      V - the type of the other stream elements
      R - the type of the resulting stream elements
      Parameters:
      other - the stream to zip this stream with
      mapper - a non-interfering, stateless function to apply to the corresponding pairs of this stream and other stream elements
      Returns:
      the new stream
      Since:
      0.5.5
      See Also:
    • zipWith

      public <V, R> StreamEx<R> zipWith(BaseStream<V,?> other, BiFunction<? super T,? super V,? extends R> mapper)
      Creates a new StreamEx which is the result of applying of the mapper BiFunction to the corresponding elements of this stream and the supplied other stream. The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel. When the resulting stream is closed, the close handlers for both input streams are invoked.

      This is a quasi-intermediate operation.

      The resulting stream finishes when either of the input streams finish: the rest of the longer stream is discarded. It's unspecified whether the rest elements of the longer stream are actually consumed.

      The stream created by this operation may have poor characteristics and parallelize badly, so it should be used only when there's no other choice. If both input streams are random-access lists or arrays, consider using zip(List, List, BiFunction) or zip(Object[], Object[], BiFunction) respectively. If you want to zip the stream with the stream of indices, consider using EntryStream.of(List) instead.

      Type Parameters:
      V - the type of the other stream elements
      R - the type of the resulting stream elements
      Parameters:
      other - the stream to zip this stream with
      mapper - a non-interfering, stateless function to apply to the corresponding pairs of this stream and other stream elements
      Returns:
      the new stream
      Since:
      0.6.7
      See Also:
    • zipWith

      public <V> EntryStream<T,V> zipWith(Stream<V> other)
      Creates a new EntryStream which keys are elements of this stream and values are the corresponding elements of the supplied other stream. The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel. When the resulting stream is closed, the close handlers for both input streams are invoked.

      This is a quasi-intermediate operation.

      The resulting stream finishes when either of the input streams finish: the rest of the longer stream is discarded. It's unspecified whether the rest elements of the longer stream are actually consumed.

      The stream created by this operation may have poor characteristics and parallelize badly, so it should be used only when there's no other choice. If both input streams are random-access lists or arrays, consider using EntryStream.zip(List, List) or EntryStream.zip(Object[], Object[]) respectively. If you want to zip the stream with the stream of indices, consider using EntryStream.of(List) instead.

      Type Parameters:
      V - the type of the other stream elements
      Parameters:
      other - the stream to zip this stream with
      Returns:
      the new stream
      Since:
      0.5.5
      See Also:
    • zipWith

      public <V> EntryStream<T,V> zipWith(BaseStream<V,?> other)
      Creates a new EntryStream which keys are elements of this stream and values are the corresponding elements of the supplied other stream. The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel. When the resulting stream is closed, the close handlers for both input streams are invoked.

      This is a quasi-intermediate operation.

      The resulting stream finishes when either of the input streams finish: the rest of the longer stream is discarded. It's unspecified whether the rest elements of the longer stream are actually consumed.

      The stream created by this operation may have poor characteristics and parallelize badly, so it should be used only when there's no other choice. If both input streams are random-access lists or arrays, consider using EntryStream.zip(List, List) or EntryStream.zip(Object[], Object[]) respectively. If you want to zip the stream with the stream of indices, consider using EntryStream.of(List) instead.

      Type Parameters:
      V - the type of the other stream elements
      Parameters:
      other - the stream to zip this stream with
      Returns:
      the new stream
      Since:
      0.6.7
      See Also:
    • headTail

      public <R> StreamEx<R> headTail(BiFunction<? super T,? super StreamEx<T>,? extends Stream<R>> mapper)
      Creates a new Stream which is the result of applying of the mapper BiFunction to the first element of the current stream (head) and the stream containing the rest elements (tail). The mapper may return null instead of empty stream.

      This is a quasi-intermediate operation with tail-stream optimization.

      The mapper function is not applied when the input stream is empty. This operation is equivalent to headTail(mapper, () -> null). Otherwise, it's applied at most once during the stream terminal operation execution. Sometimes it's useful to generate stream recursively like this:

      
       // Returns lazily-generated stream which performs scanLeft operation on the input
       static <T> StreamEx<T> scanLeft(StreamEx<T> input, BinaryOperator<T> operator) {
           return input.headTail((head, tail) -> 
               scanLeft(tail.mapFirst(cur -> operator.apply(head, cur)), operator).prepend(head));
       }

      When possible, use tail-stream optimized operations to reduce the call stack depth. In particular, the example shown above uses only headTail(), mapFirst(Function) and prepend(Object...) operations, all of them are tail-stream optimized, so it will not fail with StackOverflowError on long input stream.

      This operation might perform badly with parallel streams. Sometimes the same semantics could be expressed using other operations like withFirst(BiFunction) or mapFirst(Function) which parallelize better. Consider using these methods if it's possible in your case.

      Type Parameters:
      R - The element type of the new stream
      Parameters:
      mapper - a non-interfering function to apply to the first stream element and the stream of the rest elements which creates a new stream.
      Returns:
      the new stream
      Since:
      0.5.3
      See Also:
    • headTail

      public <R> StreamEx<R> headTail(BiFunction<? super T,? super StreamEx<T>,? extends Stream<R>> mapper, Supplier<? extends Stream<R>> supplier)
      Creates a new Stream which is the result of applying of the mapper BiFunction to the first element of the current stream (head) and the stream containing the rest elements (tail) or supplier if the current stream is empty. The mapper or supplier may return null instead of empty stream.

      This is a quasi-intermediate operation with tail-stream optimization.

      Either mapper function or supplier (but not both) is applied at most once during the stream terminal operation execution. Sometimes it's useful to generate stream recursively like this:

      
       // Stream of fixed size batches
       static <T> StreamEx<List<T>> batches(StreamEx<T> input, int size) {
           return batches(input, size, Collections.emptyList());
       }
      
       private static <T> StreamEx<List<T>> batches(StreamEx<T> input, int size, List<T> cur) {
           return input.headTail((head, tail) -> cur.size() >= size 
                   ? batches(tail, size, Arrays.asList(head)).prepend(cur)
                   : batches(tail, size, StreamEx.of(cur).append(head).toList()), 
                   () -> Stream.of(cur));
       }

      When possible, use tail-stream optimized operations to reduce the call stack depth. In particular, the example shown above uses only headTail(), and prepend(Object...) operations, both of them are tail-stream optimized, so it will not fail with StackOverflowError on long input stream.

      This operation might perform badly with parallel streams. Sometimes the same semantics could be expressed using other operations like withFirst(BiFunction) or mapFirst(Function) which parallelize better. Consider using these methods if it's possible in your case.

      Type Parameters:
      R - The element type of the new stream
      Parameters:
      mapper - a non-interfering function to apply to the first stream element and the stream of the rest elements which creates a new stream.
      supplier - a non-interfering supplier which creates a resulting stream when this stream is empty.
      Returns:
      the new stream
      Since:
      0.5.3
      See Also:
    • empty

      public static <T> StreamEx<T> empty()
      Returns an empty sequential StreamEx.
      Type Parameters:
      T - the type of stream elements
      Returns:
      an empty sequential stream
    • of

      public static <T> StreamEx<T> of(T element)
      Returns a sequential StreamEx containing a single element.
      Type Parameters:
      T - the type of stream element
      Parameters:
      element - the single element
      Returns:
      a singleton sequential stream
      See Also:
    • of

      @SafeVarargs public static <T> StreamEx<T> of(T... elements)
      Returns a sequential ordered StreamEx whose elements are the specified values.
      Type Parameters:
      T - the type of stream elements
      Parameters:
      elements - the elements of the new stream
      Returns:
      the new stream
      See Also:
    • of

      public static <T> StreamEx<T> of(T[] array, int startInclusive, int endExclusive)
      Returns a sequential StreamEx with the specified range of the specified array as its source.
      Type Parameters:
      T - the type of stream elements
      Parameters:
      array - the array, assumed to be unmodified during use
      startInclusive - the first index to cover, inclusive
      endExclusive - index immediately past the last index to cover
      Returns:
      a StreamEx for the array range
      Throws:
      ArrayIndexOutOfBoundsException - if startInclusive is negative, endExclusive is less than startInclusive, or endExclusive is greater than the array size
      Since:
      0.1.1
      See Also:
    • of

      public static <T> StreamEx<T> of(Collection<? extends T> collection)
      Returns a sequential StreamEx with given collection as its source.
      Type Parameters:
      T - the type of collection elements
      Parameters:
      collection - collection to create the stream of
      Returns:
      a sequential StreamEx over the elements in given collection
      See Also:
    • ofReversed

      public static <T> StreamEx<T> ofReversed(List<? extends T> list)
      Returns a sequential StreamEx which elements are elements of given list in descending order.

      The list elements are accessed using List.get(int), so the list should provide fast random access. The list is assumed to be unmodifiable during the stream operations.

      Type Parameters:
      T - the type of stream elements
      Parameters:
      list - list to get the elements from
      Returns:
      the new stream
    • ofReversed

      public static <T> StreamEx<T> ofReversed(T[] array)
      Returns a sequential StreamEx which elements are elements of given array in descending order.
      Type Parameters:
      T - the type of stream elements
      Parameters:
      array - array to get the elements from
      Returns:
      the new stream
    • of

      public static <T> StreamEx<T> of(Stream<T> stream)
      Returns an StreamEx object which wraps given Stream.

      The supplied stream must not be consumed or closed when this method is called. No operation must be performed on the supplied stream after it's wrapped.

      Type Parameters:
      T - the type of stream elements
      Parameters:
      stream - original stream
      Returns:
      the wrapped stream
    • of

      public static <T> StreamEx<T> of(Spliterator<? extends T> spliterator)
      Returns a sequential StreamEx created from given Spliterator.
      Type Parameters:
      T - the type of stream elements
      Parameters:
      spliterator - a spliterator to create the stream from.
      Returns:
      the new stream
      Since:
      0.3.4
    • of

      public static <T> StreamEx<T> of(Iterator<? extends T> iterator)
      Returns a sequential, ordered StreamEx created from given Iterator.

      This method is roughly equivalent to StreamEx.of(Spliterators.spliteratorUnknownSize(iterator, ORDERED)) , but may show better performance for parallel processing.

      Use this method only if you cannot provide better Stream source (like Collection or Spliterator).

      Type Parameters:
      T - the type of iterator elements
      Parameters:
      iterator - an iterator to create the stream from.
      Returns:
      the new stream
      Since:
      0.5.1
    • of

      public static <T> StreamEx<T> of(Enumeration<? extends T> enumeration)
      Returns a sequential, ordered StreamEx created from given Enumeration.

      Use this method only if you cannot provide better Stream source (like Collection or Spliterator).

      Type Parameters:
      T - the type of enumeration elements
      Parameters:
      enumeration - an enumeration to create the stream from.
      Returns:
      the new stream
      Since:
      0.5.1
    • of

      public static <T> StreamEx<T> of(Optional<? extends T> optional)
      Returns a sequential StreamEx containing an Optional value, if present, otherwise returns an empty StreamEx.
      Type Parameters:
      T - the type of stream elements
      Parameters:
      optional - the optional to create a stream of
      Returns:
      a stream with an Optional value if present, otherwise an empty stream
      Since:
      0.1.1
    • ofNullable

      public static <T> StreamEx<T> ofNullable(T element)
      Returns a sequential StreamEx containing a single element, if non-null, otherwise returns an empty StreamEx.
      Type Parameters:
      T - the type of stream elements
      Parameters:
      element - the single element
      Returns:
      a stream with a single element if the specified element is non-null, otherwise an empty stream
      Since:
      0.1.1
    • ofLines

      public static StreamEx<String> ofLines(BufferedReader reader)
      Returns a StreamEx, the elements of which are lines read from the supplied BufferedReader. The StreamEx is lazily populated, i.e., read only occurs during the terminal stream operation.

      The reader must not be operated on during the execution of the terminal stream operation. Otherwise, the result of the terminal stream operation is undefined.

      After execution of the terminal stream operation there are no guarantees that the reader will be at a specific position from which to read the next character or line.

      If an IOException is thrown when accessing the underlying BufferedReader, it is wrapped in an UncheckedIOException which will be thrown from the StreamEx method that caused the read to take place. This method will return a StreamEx if invoked on a BufferedReader that is closed. Any operation on that stream that requires reading from the BufferedReader after it is closed, will cause an UncheckedIOException to be thrown.

      Parameters:
      reader - the reader to get the lines from
      Returns:
      a StreamEx<String> providing the lines of text described by supplied BufferedReader
      See Also:
    • ofLines

      public static StreamEx<String> ofLines(Reader reader)
      Returns a StreamEx, the elements of which are lines read from the supplied Reader. The StreamEx is lazily populated, i.e., read only occurs during the terminal stream operation.

      The reader must not be operated on during the execution of the terminal stream operation. Otherwise, the result of the terminal stream operation is undefined.

      After execution of the terminal stream operation there are no guarantees that the reader will be at a specific position from which to read the next character or line.

      If an IOException is thrown when accessing the underlying Reader, it is wrapped in an UncheckedIOException which will be thrown from the StreamEx method that caused the read to take place. This method will return a StreamEx if invoked on a Reader that is closed. Any operation on that stream that requires reading from the Reader after it is closed, will cause an UncheckedIOException to be thrown.

      Parameters:
      reader - the reader to get the lines from
      Returns:
      a StreamEx<String> providing the lines of text described by supplied Reader
      See Also:
    • ofLines

      public static StreamEx<String> ofLines(Path path) throws IOException
      Read all lines from a file as a StreamEx. Bytes from the file are decoded into characters using the UTF-8 charset and the same line terminators as specified by Files.readAllLines(Path, Charset) are supported.

      After this method returns, then any subsequent I/O exception that occurs while reading from the file or when a malformed or unmappable byte sequence is read, is wrapped in an UncheckedIOException that will be thrown from the StreamEx method that caused the read to take place. In case an IOException is thrown when closing the file, it is also wrapped as an UncheckedIOException.

      The returned stream encapsulates a Reader. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed.

      Parameters:
      path - the path to the file
      Returns:
      the lines from the file as a StreamEx
      Throws:
      IOException - if an I/O error occurs opening the file
      Since:
      0.5.0
      See Also:
    • ofLines

      public static StreamEx<String> ofLines(Path path, Charset charset) throws IOException
      Read all lines from a file as a StreamEx.

      Bytes from the file are decoded into characters using the specified charset and the same line terminators as specified by Files.readAllLines(Path, Charset) are supported.

      After this method returns, then any subsequent I/O exception that occurs while reading from the file or when a malformed or unmappable byte sequence is read, is wrapped in an UncheckedIOException that will be thrown from the StreamEx method that caused the read to take place. In case an IOException is thrown when closing the file, it is also wrapped as an UncheckedIOException.

      The returned stream encapsulates a Reader. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed.

      Parameters:
      path - the path to the file
      charset - the charset to use for decoding
      Returns:
      the lines from the file as a StreamEx
      Throws:
      IOException - if an I/O error occurs opening the file
      Since:
      0.5.0
      See Also:
    • ofKeys

      public static <T> StreamEx<T> ofKeys(Map<T,?> map)
      Returns a sequential StreamEx with keySet of given Map as its source.
      Type Parameters:
      T - the type of map keys
      Parameters:
      map - input map
      Returns:
      a sequential StreamEx over the keys of given Map
      Throws:
      NullPointerException - if map is null
      See Also:
    • ofKeys

      public static <T, V> StreamEx<T> ofKeys(Map<T,V> map, Predicate<? super V> valueFilter)
      Returns a sequential StreamEx of given Map keys which corresponding values match the supplied filter.
      Type Parameters:
      T - the type of map keys and created stream elements
      V - the type of map values
      Parameters:
      map - input map
      valueFilter - a predicate used to test values
      Returns:
      a sequential StreamEx over the keys of given Map which corresponding values match the supplied filter.
      Throws:
      NullPointerException - if map is null
      See Also:
    • ofValues

      public static <T> StreamEx<T> ofValues(Map<?,T> map)
      Returns a sequential StreamEx with values of given Map as its source.
      Type Parameters:
      T - the type of map keys
      Parameters:
      map - input map
      Returns:
      a sequential StreamEx over the values of given Map
      Throws:
      NullPointerException - if map is null
      See Also:
    • ofValues

      public static <K, T> StreamEx<T> ofValues(Map<K,T> map, Predicate<? super K> keyFilter)
      Returns a sequential StreamEx of given Map values which corresponding keys match the supplied filter.
      Type Parameters:
      K - the type of map keys
      T - the type of map values and created stream elements
      Parameters:
      map - input map
      keyFilter - a predicate used to test keys
      Returns:
      a sequential StreamEx over the values of given Map which corresponding keys match the supplied filter.
      Throws:
      NullPointerException - if map is null
      See Also:
    • ofPermutations

      public static StreamEx<int[]> ofPermutations(int length)
      Returns a new StreamEx of int[] arrays containing all the possible permutations of numbers from 0 to length-1 in lexicographic order.
      Parameters:
      length - length of permutations array. Lengths bigger than 20 are not supported currently as resulting number of permutations will exceed Long.MAX_VALUE.
      Returns:
      new sequential StreamEx of possible permutations.
      Throws:
      IllegalArgumentException - if length is negative or number of possible permutations exceeds Long.MAX_VALUE.
      Since:
      0.2.2
    • ofCombinations

      public static StreamEx<int[]> ofCombinations(int n, int k)
      Returns a new StreamEx of int[] arrays containing all the possible combinations of length k consisting of numbers from 0 to n-1 in lexicographic order.

      Example: StreamEx.ofCombinations(3, 2) returns the stream of three elements: [0, 1], [0, 2] and [1, 2] in this order.

      Parameters:
      n - number of possible distinct elements
      k - number of elements in each combination
      Returns:
      new sequential stream of possible combinations. Returns an empty stream if k is bigger than n.
      Throws:
      IllegalArgumentException - if n or k is negative or number of possible combinations exceeds Long.MAX_VALUE.
      Since:
      0.6.7
    • split

      public static StreamEx<String> split(CharSequence str, Pattern pattern)
      Creates a stream from the given input sequence around matches of the given pattern.

      The stream returned by this method contains each substring of the input sequence that is terminated by another subsequence that matches this pattern or is terminated by the end of the input sequence. The substrings in the stream are in the order in which they occur in the input. Trailing empty strings will be discarded and not encountered in the stream.

      If the given pattern does not match any subsequence of the input then the resulting stream has just one element, namely the input sequence in string form.

      When there is a positive-width match at the beginning of the input sequence then an empty leading substring is included at the beginning of the stream. A zero-width match at the beginning however never produces such empty leading substring.

      If the input sequence is mutable, it must remain constant from the stream creation until the execution of the terminal stream operation. Otherwise, the result of the terminal stream operation is undefined.

      Parameters:
      str - The character sequence to be split
      pattern - The pattern to use for splitting
      Returns:
      The stream of strings computed by splitting the input around matches of this pattern
      See Also:
    • split

      public static StreamEx<String> split(CharSequence str, String regex)
      Creates a stream from the given input sequence around matches of the given pattern represented as String.

      This method is equivalent to StreamEx.split(str, Pattern.compile(regex)).

      Parameters:
      str - The character sequence to be split
      regex - The regular expression String to use for splitting
      Returns:
      The stream of strings computed by splitting the input around matches of this pattern
      See Also:
    • isNotRegexSpecialCaseStarter

      private static boolean isNotRegexSpecialCaseStarter(char ch)
    • isTransparentlyQuotableCharacter

      private static boolean isTransparentlyQuotableCharacter(char ch)
    • split

      public static StreamEx<String> split(CharSequence str, char delimiter)
      Creates a stream from the given input sequence around matches of the given character.

      This method is equivalent to StreamEx.split(str, delimiter, true).

      Parameters:
      str - The character sequence to be split
      delimiter - The delimiter character to use for splitting
      Returns:
      The stream of strings computed by splitting the input around the delimiters
      Since:
      0.5.1
      See Also:
    • split

      public static StreamEx<String> split(CharSequence str, char delimiter, boolean trimEmpty)
      Creates a stream from the given input sequence around matches of the given character.

      The stream returned by this method contains each substring of the input sequence that is terminated by supplied delimiter character or is terminated by the end of the input sequence. The substrings in the stream are in the order in which they occur in the input. If the trimEmpty parameter is true, trailing empty strings will be discarded and not encountered in the stream.

      If the given delimiter character does not appear in the input then the resulting stream has just one element, namely the input sequence in string form.

      If the input sequence is mutable, it must remain constant from the stream creation until the execution of the terminal stream operation. Otherwise, the result of the terminal stream operation is undefined.

      Parameters:
      str - The character sequence to be split
      delimiter - The delimiter character to use for splitting
      trimEmpty - If true, trailing empty strings will be discarded
      Returns:
      The stream of strings computed by splitting the input around the delimiters
      Since:
      0.5.1
      See Also:
    • iterate

      public static <T> StreamEx<T> iterate(T seed, UnaryOperator<T> f)
      Returns an infinite sequential ordered StreamEx produced by iterative application of a function f to an initial element seed, producing a StreamEx consisting of seed, f(seed), f(f(seed)), etc.

      The first element (position 0) in the StreamEx will be the provided seed. For n > 0, the element at position n, will be the result of applying the function f to the element at position n - 1.

      Type Parameters:
      T - the type of stream elements
      Parameters:
      seed - the initial element
      f - a function to be applied to the previous element to produce a new element
      Returns:
      a new sequential StreamEx
      See Also:
    • iterate

      public static <T> StreamEx<T> iterate(T seed, Predicate<? super T> predicate, UnaryOperator<T> f)
      Returns a sequential ordered StreamEx produced by iterative application of a function to an initial element, conditioned on satisfying the supplied predicate. The stream terminates as soon as the predicate function returns false.

      StreamEx.iterate should produce the same sequence of elements as produced by the corresponding for-loop:

      
           for (T index=seed; predicate.test(index); index = f.apply(index)) { 
               ... 
           }
       

      The resulting sequence may be empty if the predicate does not hold on the seed value. Otherwise, the first element will be the supplied seed value, the next element (if present) will be the result of applying the function f to the seed value, and so on iteratively until the predicate indicates that the stream should terminate.

      Type Parameters:
      T - the type of stream elements
      Parameters:
      seed - the initial element
      predicate - a predicate to apply to elements to determine when the stream must terminate.
      f - a function to be applied to the previous element to produce a new element
      Returns:
      a new sequential StreamEx
      Since:
      0.6.0
      See Also:
    • generate

      public static <T> StreamEx<T> generate(Supplier<T> s)
      Returns an infinite sequential unordered StreamEx where each element is generated by the provided Supplier. This is suitable for generating constant streams, streams of random elements, etc.
      Type Parameters:
      T - the type of stream elements
      Parameters:
      s - the Supplier of generated elements
      Returns:
      a new infinite sequential unordered StreamEx
      See Also:
    • produce

      public static <T> StreamEx<T> produce(Predicate<Consumer<? super T>> producer)
      Return an ordered stream produced by consecutive calls of the supplied producer until it returns false.

      The producer function may call the passed consumer any number of times and return true if the producer should be called again or false otherwise. It's guaranteed that the producer will not be called anymore, once it returns false.

      This method is particularly useful when producer changes the mutable object which should be left in known state after the full stream consumption. For example, the following code could be used to drain elements from the queue until it's empty or sentinel is reached (consuming the sentinel):

      
       return StreamEx.produce(action -> {
         T next = queue.poll();
         if(next == null || next.equals(sentinel))
             return false;
         action.accept(next);
         return true;
       });

      Note however that if a short-circuiting operation is used, then the final state of the mutable object cannot be guaranteed.

      Type Parameters:
      T - the type of the resulting stream elements
      Parameters:
      producer - a predicate which calls the passed consumer to emit stream element(s) and returns true if its producer should be applied again.
      Returns:
      the new stream
      Since:
      0.6.0
    • constant

      public static <T> StreamEx<T> constant(T value, long length)
      Returns a sequential unordered StreamEx of given length which elements are equal to supplied value.
      Type Parameters:
      T - the type of stream elements
      Parameters:
      value - the constant value
      length - the length of the stream
      Returns:
      a new StreamEx
      Since:
      0.1.2
    • ofPairs

      public static <U, T> StreamEx<T> ofPairs(List<U> list, BiFunction<? super U,? super U,? extends T> mapper)
      Returns a sequential ordered StreamEx containing the results of applying the given mapper function to the all possible pairs of elements taken from the provided list.

      The indices of two elements supplied to the mapper function are always ordered: first element index is strictly less than the second element index. The pairs are lexicographically ordered. For example, for the list of three elements the stream of three elements is created: mapper.apply(list.get(0), list.get(1)), mapper.apply(list.get(0), list.get(2)) and mapper.apply(list.get(1), list.get(2)). The number of elements in the resulting stream is list.size()*(list.size()+1L)/2.

      The list values are accessed using List.get(int), so the list should provide fast random access. The list is assumed to be unmodifiable during the stream operations.

      Type Parameters:
      U - type of the list elements
      T - type of the stream elements
      Parameters:
      list - a list to take the elements from
      mapper - a non-interfering, stateless function to apply to each pair of list elements.
      Returns:
      a new StreamEx
      Since:
      0.3.6
      See Also:
    • ofPairs

      public static <U, T> StreamEx<T> ofPairs(U[] array, BiFunction<? super U,? super U,? extends T> mapper)
      Returns a sequential ordered StreamEx containing the results of applying the given mapper function to the all possible pairs of elements taken from the provided array.

      The indices of two array elements supplied to the mapper function are always ordered: first element index is strictly less than the second element index. The pairs are lexicographically ordered. For example, for the array of three elements the stream of three elements is created: mapper.apply(array[0], array[1]), mapper.apply(array[0], array[2]) and mapper.apply(array[1], array[2]). The number of elements in the resulting stream is array.length*(array.length+1L)/2.

      Type Parameters:
      U - type of the array elements
      T - type of the stream elements
      Parameters:
      array - an array to take the elements from
      mapper - a non-interfering, stateless function to apply to each pair of array elements.
      Returns:
      a new StreamEx
      Since:
      0.3.6
      See Also:
    • zip

      public static <U, V, T> StreamEx<T> zip(List<U> first, List<V> second, BiFunction<? super U,? super V,? extends T> mapper)
      Returns a sequential StreamEx containing the results of applying the given function to the corresponding pairs of values in given two lists.

      The list values are accessed using List.get(int), so the lists should provide fast random access. The lists are assumed to be unmodifiable during the stream operations.

      Type Parameters:
      U - the type of the first list elements
      V - the type of the second list elements
      T - the type of the resulting stream elements
      Parameters:
      first - the first list, assumed to be unmodified during use
      second - the second list, assumed to be unmodified during use
      mapper - a non-interfering, stateless function to apply to each pair of the corresponding list elements.
      Returns:
      a new StreamEx
      Throws:
      IllegalArgumentException - if length of the lists differs.
      Since:
      0.2.1
      See Also:
    • zip

      public static <U, V, T> StreamEx<T> zip(U[] first, V[] second, BiFunction<? super U,? super V,? extends T> mapper)
      Returns a sequential StreamEx containing the results of applying the given function to the corresponding pairs of values in given two arrays.
      Type Parameters:
      U - the type of the first array elements
      V - the type of the second array elements
      T - the type of the resulting stream elements
      Parameters:
      first - the first array
      second - the second array
      mapper - a non-interfering, stateless function to apply to each pair of the corresponding array elements.
      Returns:
      a new StreamEx
      Throws:
      IllegalArgumentException - if length of the arrays differs.
      Since:
      0.2.1
      See Also:
    • ofTree

      public static <T> StreamEx<T> ofTree(T root, Function<T,Stream<T>> mapper)
      Return a new StreamEx containing all the nodes of tree-like data structure in depth-first order.

      The streams created by mapper may be automatically closed after its contents already consumed and unnecessary anymore. It's not guaranteed that all created streams will be closed during the stream terminal operation. If it's necessary to close all the created streams, call the close() method of the resulting stream returned by ofTree().

      Type Parameters:
      T - the type of tree nodes
      Parameters:
      root - root node of the tree
      mapper - a non-interfering, stateless function to apply to each tree node which returns null for leaf nodes or stream of direct children for non-leaf nodes.
      Returns:
      the new sequential ordered stream
      Since:
      0.2.2
      See Also:
    • ofTree

      public static <T, TT extends T> StreamEx<T> ofTree(T root, Class<TT> collectionClass, Function<TT,Stream<T>> mapper)
      Return a new StreamEx containing all the nodes of tree-like data structure in depth-first order.

      The streams created by mapper may be automatically closed after its contents already consumed and unnecessary anymore. It's not guaranteed that all created streams will be closed during the stream terminal operation. If it's necessary to close all the created streams, call the close() method of the resulting stream returned by ofTree().

      Type Parameters:
      T - the base type of tree nodes
      TT - the subtype of composite tree nodes which may have children
      Parameters:
      root - root node of the tree
      collectionClass - a class representing the composite tree node
      mapper - a non-interfering, stateless function to apply to each composite tree node which returns stream of direct children. May return null if the given node has no children.
      Returns:
      the new sequential ordered stream
      Since:
      0.2.2
      See Also:
    • ofSubLists

      public static <T> StreamEx<List<T>> ofSubLists(List<T> source, int length)
      Returns a new StreamEx which consists of non-overlapping sublists of given source list having the specified length (the last sublist may be shorter).

      This method calls List.subList(int, int) internally, so source list must have it properly implemented as well as provide fast random access.

      This method is equivalent to StreamEx.ofSubLists(source, length, length).

      Type Parameters:
      T - the type of source list elements.
      Parameters:
      source - the source list
      length - the length of each sublist except possibly the last one (must be positive number).
      Returns:
      the new stream of sublists.
      Throws:
      IllegalArgumentException - if length is negative or zero.
      Since:
      0.3.3
      See Also:
    • ofSubLists

      public static <T> StreamEx<List<T>> ofSubLists(List<T> source, int length, int shift)
      Returns a new StreamEx which consists of possibly-overlapping sublists of given source list having the specified length with given shift value.

      This method calls List.subList(int, int) internally, so source list must have it properly implemented as well as provide fast random access.

      The shift value specifies how many elements the next sublist is shifted relative to the previous one. If the shift value is greater than one, then the last sublist might be shorter than the specified length value. If the shift value is greater than the length, some elements will not appear in sublists at all.

      Type Parameters:
      T - the type of source list elements.
      Parameters:
      source - the source list
      length - the length of each sublist except possibly the last one (must be positive number).
      shift - the number of elements the next sublist is shifted relative to the previous one (must be positive number).
      Returns:
      the new stream of sublists.
      Throws:
      IllegalArgumentException - if length is negative or zero.
      Since:
      0.3.7
      See Also:
    • cartesianProduct

      public static <T> StreamEx<List<T>> cartesianProduct(Collection<? extends Collection<T>> source)
      Returns a new StreamEx which elements are List objects containing all possible tuples of the elements of supplied collection of collections. The whole stream forms an n-fold Cartesian product (or cross-product) of the input collections.

      Every stream element is the List of the same size as supplied collection. The first element in the list is taken from the first collection which appears in source and so on. The elements are ordered lexicographically according to the order of the input collections.

      There are no guarantees on the type, mutability, serializability, or thread-safety of the List elements. It's however guaranteed that each element is the distinct object.

      The supplied collection is assumed to be unchanged during the operation.

      Type Parameters:
      T - the type of the elements
      Parameters:
      source - the input collection of collections which is used to generate the cross-product.
      Returns:
      the new stream of lists.
      Since:
      0.3.8
      See Also:
    • cartesianProduct

      public static <T, U> StreamEx<U> cartesianProduct(Collection<? extends Collection<T>> source, U identity, BiFunction<U,? super T,U> accumulator)
      Returns a new StreamEx which elements are results of reduction of all possible tuples composed of the elements of supplied collection of collections. The whole stream forms an n-fold Cartesian product (or cross-product) of the input collections.

      The reduction is performed using the provided identity object and the accumulator function which is capable to accumulate new element. The accumulator function must not modify the previous accumulated value, but must produce new value instead. That's because partially accumulated values are reused for subsequent elements.

      This method is equivalent to the following:

       StreamEx.cartesianProduct(source).map(list -> StreamEx.of(list).foldLeft(identity, accumulator))
       

      However, it may perform much faster as partial reduction results are reused.

      The supplied collection is assumed to be unchanged during the operation.

      Type Parameters:
      T - the type of the input elements
      U - the type of the elements of the resulting stream
      Parameters:
      source - the input collection of collections which is used to generate the cross-product.
      identity - the identity value
      accumulator - a non-interfering , stateless function for incorporating an additional element from source collection into a stream element.
      Returns:
      the new stream.
      Since:
      0.4.0
      See Also:
    • cartesianPower

      public static <T> StreamEx<List<T>> cartesianPower(int n, Collection<T> source)
      Returns a new StreamEx which elements are List objects containing all possible n-tuples of the elements of supplied collection. The whole stream forms an n-fold Cartesian product of input collection with itself or n-ary Cartesian power of the input collection.

      Every stream element is the List of the supplied size. The elements are ordered lexicographically according to the order of the input collection.

      There are no guarantees on the type, mutability, serializability, or thread-safety of the List elements. It's however guaranteed that each element is the distinct object.

      The supplied collection is assumed to be unchanged during the operation.

      Type Parameters:
      T - the type of the elements
      Parameters:
      n - the size of the List elements of the resulting stream.
      source - the input collection of collections which is used to generate the Cartesian power.
      Returns:
      the new stream of lists.
      Since:
      0.3.8
      See Also:
    • cartesianPower

      public static <T, U> StreamEx<U> cartesianPower(int n, Collection<T> source, U identity, BiFunction<U,? super T,U> accumulator)
      Returns a new StreamEx which elements are results of reduction of all possible n-tuples composed of the elements of supplied collections. The whole stream forms an n-fold Cartesian product of input collection with itself or n-ary Cartesian power of the input collection.

      The reduction is performed using the provided identity object and the accumulator function which is capable to accumulate new element. The accumulator function must not modify the previous accumulated value, but must produce new value instead. That's because partially accumulated values are reused for subsequent elements.

      This method is equivalent to the following:

       StreamEx.cartesianPower(n, source).map(list -> StreamEx.of(list).foldLeft(identity, accumulator))
       

      However, it may perform much faster as partial reduction results are reused.

      The supplied collection is assumed to be unchanged during the operation.

      Type Parameters:
      T - the type of the input elements
      U - the type of the elements of the resulting stream
      Parameters:
      n - the number of elements to incorporate into single element of the resulting stream.
      source - the input collection of collections which is used to generate the Cartesian power.
      identity - the identity value
      accumulator - a non-interfering , stateless function for incorporating an additional element from source collection into a stream element.
      Returns:
      the new stream.
      Since:
      0.4.0
      See Also: