Class StreamEx<T>
- Object
-
- AbstractStreamEx<T,StreamEx<T>>
-
- StreamEx<T>
-
- Type Parameters:
T
- the type of the stream elements
- All Implemented Interfaces:
AutoCloseable
,Iterable<T>
,BaseStream<T,Stream<T>>
,Stream<T>
public class StreamEx<T> extends AbstractStreamEx<T,StreamEx<T>>
AStream
implementation with additional functionality.While
StreamEx
implementsIterable
, it is not a general-purposeIterable
as it supports only a singleIterator
; invoking theiterator
method to obtain a second or subsequent iterator throwsIllegalStateException
.- Author:
- Tagir Valeev
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static interface
StreamEx.Emitter<T>
A helper interface to build a new stream by emitting elements and creating new emitters in a chain.-
Nested classes/interfaces inherited from interface Stream
Stream.Builder<T extends Object>
-
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description StreamEx<T>
append(Collection<? extends T> collection)
Returns a newStreamEx
which is a concatenation of this stream and the stream created from supplied collection.StreamEx<T>
append(T value)
Returns a newStreamEx
which is a concatenation of this stream and the supplied value.StreamEx<T>
append(T... values)
Returns a newStreamEx
which is a concatenation of this stream and the supplied values.static <T> StreamEx<List<T>>
cartesianPower(int n, Collection<T> source)
Returns a newStreamEx
which elements areList
objects containing all possible n-tuples of the elements of supplied collection.static <T,U>
StreamEx<U>cartesianPower(int n, Collection<T> source, U identity, BiFunction<U,? super T,U> accumulator)
Returns a newStreamEx
which elements are results of reduction of all possible n-tuples composed from the elements of supplied collections.static <T> StreamEx<List<T>>
cartesianProduct(Collection<? extends Collection<T>> source)
Returns a newStreamEx
which elements areList
objects containing all possible tuples of the elements of supplied collection of collections.static <T,U>
StreamEx<U>cartesianProduct(Collection<? extends Collection<T>> source, U identity, BiFunction<U,? super T,U> accumulator)
Returns a newStreamEx
which elements are results of reduction of all possible tuples composed from the elements of supplied collection of collections.void
close()
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.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.<R,A>
StreamEx<R>collapse(BiPredicate<? super T,? super T> collapsible, Collector<? super T,A,R> collector)
Perform a partial mutable reduction using the suppliedCollector
on a series of adjacent elements.static <T> StreamEx<T>
constant(T value, long length)
Returns a sequential unorderedStreamEx
of given length which elements are equal to supplied value.<V> EntryStream<T,V>
cross(Collection<? extends V> other)
Performs a cross product of current stream with specifiedCollection
of elements.<V> EntryStream<T,V>
cross(Function<? super T,? extends Stream<? extends V>> mapper)
Creates a newEntryStream
whose keys are elements of current stream and corresponding values are supplied by given function.<V> EntryStream<T,V>
cross(V... other)
Performs a cross product of current stream with specified array of elements.static <T> StreamEx<T>
empty()
Returns an empty sequentialStreamEx
.<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.<K,V>
EntryStream<K,V>flatMapToEntry(Function<? super T,? extends Map<K,V>> mapper)
Creates a newEntryStream
populated from entries of maps produced by supplied mapper function which is applied to the every element of this stream.void
forPairs(BiConsumer<? super T,? super T> action)
Performs an action for each adjacent pair of elements of this stream.static <T> StreamEx<T>
generate(Supplier<T> s)
Returns an infinite sequential unorderedStreamEx
where each element is generated by the providedSupplier
.<K> Map<K,List<T>>
groupingBy(Function<? super T,? extends K> classifier)
Returns aMap
whose keys are the values resulting from applying the classification function to the input elements, and whose corresponding values areList
s containing the input elements which map to the associated key under the classification function.<K,D,M extends Map<K,D>>
MgroupingBy(Function<? super T,? extends K> classifier, Supplier<M> mapFactory, Collector<? super T,?,D> downstream)
Returns aMap
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.<K,D>
Map<K,D>groupingBy(Function<? super T,? extends K> classifier, Collector<? super T,?,D> downstream)
Returns aMap
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.<K,C extends Collection<T>>
Map<K,C>groupingTo(Function<? super T,? extends K> classifier, Supplier<C> collectionFactory)
Returns aMap
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.<K,C extends Collection<T>,M extends Map<K,C>>
MgroupingTo(Function<? super T,? extends K> classifier, Supplier<M> mapFactory, Supplier<C> collectionFactory)
Returns aMap
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.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.boolean
has(T value)
Returns true if this stream contains the specified value.<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 mapperBiFunction
to the first element of the current stream (head) and the stream containing the rest elements (tail).<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 mapperBiFunction
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.StreamEx<T>
ifEmpty(T... values)
Returns a stream which contents is the same as this stream, except the case when this stream is empty.<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.<C extends Collection<? super T>>
Cinto(C collection)
Drains the stream content into the supplied collection.boolean
isParallel()
static <T> StreamEx<T>
iterate(T seed, Predicate<? super T> predicate, UnaryOperator<T> f)
Returns a sequential orderedStreamEx
produced by iterative application of a function to an initial element, conditioned on satisfying the supplied predicate.static <T> StreamEx<T>
iterate(T seed, UnaryOperator<T> f)
Returns an infinite sequential orderedStreamEx
produced by iterative application of a functionf
to an initial elementseed
, producing aStreamEx
consisting ofseed
,f(seed)
,f(f(seed))
, etc.String
joining()
Returns aString
which is the concatenation of the results of callingString.valueOf(Object)
on each element of this stream in encounter order.String
joining(CharSequence delimiter)
Returns aString
which is the concatenation of the results of callingString.valueOf(Object)
on each element of this stream, separated by the specified delimiter, in encounter order.String
joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
Returns aString
which is the concatenation of the results of callingString.valueOf(Object)
on each element of this stream, separated by the specified delimiter, with the specified prefix and suffix in encounter order.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.<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 usingfirstMapper
function and other elements are transformed usingnotFirstMapper
function.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.<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 usinglastMapper
function and other elements are transformed usingnotLastMapper
function.<K,V>
EntryStream<K,V>mapToEntry(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valueMapper)
Returns anEntryStream
consisting of theMap.Entry
objects which keys and values are results of applying the given functions to the elements of this stream.<V> EntryStream<T,V>
mapToEntry(Function<? super T,? extends V> valueMapper)
Returns anEntryStream
consisting of theMap.Entry
objects which keys are elements of this stream and values are results of applying the given function to the elements of this stream.StreamEx<T>
nonNull()
Returns a stream consisting of the elements of this stream that aren't null.static <T> StreamEx<T>
of(Collection<? extends T> collection)
Returns a sequentialStreamEx
with given collection as its source.static <T> StreamEx<T>
of(Enumeration<? extends T> enumeration)
Returns a sequential, orderedStreamEx
created from givenEnumeration
.static <T> StreamEx<T>
of(Iterator<? extends T> iterator)
static <T> StreamEx<T>
of(Optional<? extends T> optional)
Returns a sequentialStreamEx
containing anOptional
value, if present, otherwise returns an emptyStreamEx
.static <T> StreamEx<T>
of(Spliterator<? extends T> spliterator)
Returns a sequentialStreamEx
created from givenSpliterator
.static <T> StreamEx<T>
of(Stream<T> stream)
static <T> StreamEx<T>
of(T element)
Returns a sequentialStreamEx
containing a single element.static <T> StreamEx<T>
of(T... elements)
Returns a sequential orderedStreamEx
whose elements are the specified values.static <T> StreamEx<T>
of(T[] array, int startInclusive, int endExclusive)
Returns a sequentialStreamEx
with the specified range of the specified array as its source.static StreamEx<int[]>
ofCombinations(int n, int k)
Returns a newStreamEx
ofint[]
arrays containing all the possible combinations of lengthk
consisting of numbers from 0 ton-1
in lexicographic order.static <T> StreamEx<T>
ofKeys(Map<T,?> map)
Returns a sequentialStreamEx
with keySet of givenMap
as its source.static <T,V>
StreamEx<T>ofKeys(Map<T,V> map, Predicate<? super V> valueFilter)
Returns a sequentialStreamEx
of givenMap
keys which corresponding values match the supplied filter.static StreamEx<String>
ofLines(BufferedReader reader)
Returns aStreamEx
, the elements of which are lines read from the suppliedBufferedReader
.static StreamEx<String>
ofLines(Reader reader)
Returns aStreamEx
, the elements of which are lines read from the suppliedReader
.static StreamEx<String>
ofLines(Path path)
Read all lines from a file as aStreamEx
.static StreamEx<String>
ofLines(Path path, Charset charset)
Read all lines from a file as aStreamEx
.static <T> StreamEx<T>
ofNullable(T element)
Returns a sequentialStreamEx
containing a single element, if non-null, otherwise returns an emptyStreamEx
.static <U,T>
StreamEx<T>ofPairs(List<U> list, BiFunction<? super U,? super U,? extends T> mapper)
Returns a sequential orderedStreamEx
containing the results of applying the given mapper function to the all possible pairs of elements taken from the provided list.static <U,T>
StreamEx<T>ofPairs(U[] array, BiFunction<? super U,? super U,? extends T> mapper)
Returns a sequential orderedStreamEx
containing the results of applying the given mapper function to the all possible pairs of elements taken from the provided array.static StreamEx<int[]>
ofPermutations(int length)
Returns a newStreamEx
ofint[]
arrays containing all the possible permutations of numbers from 0 to length-1 in lexicographic order.static <T> StreamEx<T>
ofReversed(List<? extends T> list)
Returns a sequentialStreamEx
which elements are elements of given list in descending order.static <T> StreamEx<T>
ofReversed(T[] array)
Returns a sequentialStreamEx
which elements are elements of given array in descending order.static <T> StreamEx<List<T>>
ofSubLists(List<T> source, int length)
Returns a newStreamEx
which consists of non-overlapping sublists of given source list having the specified length (the last sublist may be shorter).static <T> StreamEx<List<T>>
ofSubLists(List<T> source, int length, int shift)
Returns a newStreamEx
which consists of possibly-overlapping sublists of given source list having the specified length with given shift value.static <T,TT extends T>
StreamEx<T>ofTree(T root, Class<TT> collectionClass, Function<TT,Stream<T>> mapper)
Return a newStreamEx
containing all the nodes of tree-like data structure in depth-first order.static <T> StreamEx<T>
ofTree(T root, Function<T,Stream<T>> mapper)
Return a newStreamEx
containing all the nodes of tree-like data structure in depth-first order.static <T> StreamEx<T>
ofValues(Map<?,T> map)
Returns a sequentialStreamEx
with values of givenMap
as its source.static <K,T>
StreamEx<T>ofValues(Map<K,T> map, Predicate<? super K> keyFilter)
Returns a sequentialStreamEx
of givenMap
values which corresponding keys match the supplied filter.Map<Boolean,List<T>>
partitioningBy(Predicate<? super T> predicate)
Returns aMap<Boolean, List<T>>
which contains two partitions of the input elements according to aPredicate
.<D> Map<Boolean,D>
partitioningBy(Predicate<? super T> predicate, Collector<? super T,?,D> downstream)
Returns aMap<Boolean, D>
which contains two partitions of the input elements according to aPredicate
, which are reduced according to the suppliedCollector
.<C extends Collection<T>>
Map<Boolean,C>partitioningTo(Predicate<? super T> predicate, Supplier<C> collectionFactory)
Returns aMap<Boolean, C>
which contains two partitions of the input elements according to aPredicate
.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.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.StreamEx<T>
prepend(Collection<? extends T> collection)
Returns a newStreamEx
which is a concatenation of the stream created from supplied collection and this stream.StreamEx<T>
prepend(T value)
Returns a newStreamEx
which is a concatenation of supplied value and this stream.StreamEx<T>
prepend(T... values)
Returns a newStreamEx
which is a concatenation of supplied values and this stream.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.<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.StreamEx<T>
reverseSorted()
Returns aStreamEx
consisting of the elements of this stream, sorted according to reverse natural order.EntryStream<T,Long>
runLengths()
Collapses adjacent equal elements and returns anEntryStream
where keys are input elements and values specify how many elements were collapsed.<TT> StreamEx<TT>
select(Class<TT> clazz)
Returns a stream consisting of the elements of this stream which are instances of given class.static StreamEx<String>
split(CharSequence str, char delimiter)
Creates a stream from the given input sequence around matches of the given character.static StreamEx<String>
split(CharSequence str, char delimiter, boolean trimEmpty)
Creates a stream from the given input sequence around matches of the given character.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.static StreamEx<String>
split(CharSequence str, Pattern pattern)
Creates a stream from the given input sequence around matches of the given pattern.Spliterator<T>
spliterator()
<A> A[]
toArray(A[] emptyArray)
Returns an array containing all the stream elements.<A> A[]
toArray(Class<A> elementClass)
Returns an array containing all the stream elements using the supplied element type class to allocate an array.<U,C extends Collection<U>>
CtoFlatCollection(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.<U> List<U>
toFlatList(Function<? super T,? extends Collection<U>> mapper)
Returns aList
which contains all the elements of the collections generated by provided mapper from each element of this stream.<K,V>
Map<K,V>toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valMapper)
Returns aMap
whose keys and values are the result of applying the provided mapping functions to the input elements.<K,V>
Map<K,V>toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valMapper, BinaryOperator<V> mergeFunction)
Returns aMap
whose keys and values are the result of applying the provided mapping functions to the input elements.<V> Map<T,V>
toMap(Function<? super T,? extends V> valMapper)
Returns aMap
whose keys are elements from this stream and values are the result of applying the provided mapping functions to the input elements.<K,V>
NavigableMap<K,V>toNavigableMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valMapper)
Returns aNavigableMap
whose keys and values are the result of applying the provided mapping functions to the input elements.<K,V>
NavigableMap<K,V>toNavigableMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valMapper, BinaryOperator<V> mergeFunction)
Returns aNavigableMap
whose keys and values are the result of applying the provided mapping functions to the input elements.<V> NavigableMap<T,V>
toNavigableMap(Function<? super T,? extends V> valMapper)
Returns aNavigableMap
whose keys are elements from this stream and values are the result of applying the provided mapping functions to the input elements.<K,V>
SortedMap<K,V>toSortedMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valMapper)
Returns aSortedMap
whose keys and values are the result of applying the provided mapping functions to the input elements.<K,V>
SortedMap<K,V>toSortedMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valMapper, BinaryOperator<V> mergeFunction)
Returns aSortedMap
whose keys and values are the result of applying the provided mapping functions to the input elements.<V> SortedMap<T,V>
toSortedMap(Function<? super T,? extends V> valMapper)
Returns aSortedMap
whose keys are elements from this stream and values are the result of applying the provided mapping functions to the input elements.EntryStream<T,T>
withFirst()
Creates anEntryStream
consisting of theMap.Entry
objects which keys are all the same and equal to the first element of this stream and values are the rest elements of this stream.<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 the first element and every other element of this stream.StreamEx<T>
without(T value)
Returns a stream consisting of the elements of this stream that don't equal to the given value.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.static <U,V,T>
StreamEx<T>zip(List<U> first, List<V> second, BiFunction<? super U,? super V,? extends T> mapper)
Returns a sequentialStreamEx
containing the results of applying the given function to the corresponding pairs of values in given two lists.static <U,V,T>
StreamEx<T>zip(U[] first, V[] second, BiFunction<? super U,? super V,? extends T> mapper)
Returns a sequentialStreamEx
containing the results of applying the given function to the corresponding pairs of values in given two arrays.<V> EntryStream<T,V>
zipWith(BaseStream<V,?> other)
Creates a newEntryStream
which keys are elements of this stream and values are the corresponding elements of the supplied other stream.<V,R>
StreamEx<R>zipWith(BaseStream<V,?> other, BiFunction<? super T,? super V,? extends R> mapper)
Creates a newStreamEx
which is the result of applying of the mapperBiFunction
to the corresponding elements of this stream and the supplied other stream.<V> EntryStream<T,V>
zipWith(Stream<V> other)
Creates a newEntryStream
which keys are elements of this stream and values are the corresponding elements of the supplied other stream.<V,R>
StreamEx<R>zipWith(Stream<V> other, BiFunction<? super T,? super V,? extends R> mapper)
Creates a newStreamEx
which is the result of applying of the mapperBiFunction
to the corresponding elements of this stream and the supplied other stream.-
Methods inherited from class AbstractStreamEx
allMatch, anyMatch, append, chain, collect, collect, count, distinct, distinct, distinct, dropWhile, filter, findAny, findAny, findFirst, findFirst, flatArray, flatCollection, flatMap, flatMapToDouble, flatMapToInt, flatMapToLong, foldLeft, foldLeft, foldRight, foldRight, forEach, forEachOrdered, ifEmpty, indexOf, indexOf, intersperse, iterator, limit, map, mapPartial, mapToDouble, mapToInt, mapToLong, max, maxBy, maxByDouble, maxByInt, maxByLong, min, minBy, minByDouble, minByInt, minByLong, noneMatch, onClose, pairMap, parallel, parallel, peek, prefix, prepend, reduce, reduce, reduce, reduceWithZero, reduceWithZero, remove, reverseSorted, scanLeft, scanLeft, scanRight, scanRight, sequential, skip, sorted, sorted, sortedBy, sortedByDouble, sortedByInt, sortedByLong, takeWhile, takeWhileInclusive, toArray, toArray, toCollection, toCollectionAndThen, toImmutableList, toImmutableSet, toList, toListAndThen, toSet, toSetAndThen, unordered
-
Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
Methods inherited from interface BaseStream
close, isParallel, spliterator
-
Methods inherited from interface Iterable
spliterator
-
-
-
-
Method Detail
-
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 classAbstractStreamEx<T,StreamEx<T>>
- Returns:
- the new stream
- See Also:
AbstractStreamEx.filter(Predicate)
,AbstractStreamEx.remove(Predicate)
,select(Class)
-
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:
AbstractStreamEx.filter(Predicate)
-
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:
AbstractStreamEx.remove(Predicate)
-
mapToEntry
public <V> EntryStream<T,V> mapToEntry(Function<? super T,? extends V> valueMapper)
Returns anEntryStream
consisting of theMap.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
- TheEntry
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 anEntryStream
consisting of theMap.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
- TheEntry
key typeV
- TheEntry
value type- Parameters:
keyMapper
- a non-interfering, stateless function to apply to each elementvalueMapper
- 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 usingfirstMapper
function and other elements are transformed usingnotFirstMapper
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 elementnotFirstMapper
- a non-interfering , stateless function to apply to all elements except the first one.- Returns:
- the new stream
- Since:
- 0.6.0
- See Also:
mapFirst(Function)
-
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 usinglastMapper
function and other elements are transformed usingnotLastMapper
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:
mapFirst(Function)
-
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 newEntryStream
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 ofMap
keys.V
- the type ofMap
values.- Parameters:
mapper
- a non-interfering, stateless function to apply to each element which produces aMap
of the entries corresponding to the single element of the current stream. The mapper function may return null or emptyMap
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 theEntryStream
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 specifiedCollection
of elements. As a result theEntryStream
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 newEntryStream
whose keys are elements of current stream and corresponding values are supplied by given function. Each mapped stream isclosed
after its contents have been placed into this stream. (If a mapped stream isnull
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 aMap
whose keys are the values resulting from applying the classification function to the input elements, and whose corresponding values areList
s 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
orList
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(Function, Collector)
,Collectors.groupingBy(Function)
,Collectors.groupingByConcurrent(Function)
-
groupingBy
public <K,D> Map<K,D> groupingBy(Function<? super T,? extends K> classifier, Collector<? super T,?,D> downstream)
Returns aMap
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 keysD
- the result type of the downstream reduction- Parameters:
classifier
- the classifier function mapping input elements to keysdownstream
- aCollector
implementing the downstream reduction- Returns:
- a
Map
containing the results of the group-by operation - See Also:
groupingBy(Function)
,Collectors.groupingBy(Function, Collector)
,Collectors.groupingByConcurrent(Function, Collector)
-
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 aMap
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 keysD
- the result type of the downstream reductionM
- the type of the resultingMap
- Parameters:
classifier
- the classifier function mapping input elements to keysmapFactory
- a function which, when called, produces a new emptyMap
of the desired typedownstream
- aCollector
implementing the downstream reduction- Returns:
- a
Map
containing the results of the group-by operation - See Also:
groupingBy(Function)
,Collectors.groupingBy(Function, Supplier, Collector)
,Collectors.groupingByConcurrent(Function, Supplier, Collector)
-
groupingTo
public <K,C extends Collection<T>> Map<K,C> groupingTo(Function<? super T,? extends K> classifier, Supplier<C> collectionFactory)
Returns aMap
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 keysC
- the type of the collection used in resultingMap
values- Parameters:
classifier
- the classifier function mapping input elements to keyscollectionFactory
- a function which returns a new emptyCollection
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:
groupingBy(Function, Collector)
,Collectors.groupingBy(Function, Collector)
,Collectors.groupingByConcurrent(Function, Collector)
-
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 aMap
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 keysC
- the type of the collection used in resultingMap
valuesM
- the type of the resultingMap
- Parameters:
classifier
- the classifier function mapping input elements to keysmapFactory
- a function which, when called, produces a new emptyMap
of the desired typecollectionFactory
- a function which returns a new emptyCollection
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(Function, Supplier)
,Collectors.groupingBy(Function, Supplier, Collector)
,Collectors.groupingByConcurrent(Function, Supplier, Collector)
-
partitioningBy
public Map<Boolean,List<T>> partitioningBy(Predicate<? super T> predicate)
Returns aMap<Boolean, List<T>>
which contains two partitions of the input elements according to aPredicate
.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>>
whichBoolean.TRUE
key is mapped to the list of the stream elements for which predicate is true andBoolean.FALSE
key is mapped to the list of all other stream elements. - Since:
- 0.2.2
- See Also:
partitioningBy(Predicate, Collector)
,Collectors.partitioningBy(Predicate)
-
partitioningBy
public <D> Map<Boolean,D> partitioningBy(Predicate<? super T> predicate, Collector<? super T,?,D> downstream)
Returns aMap<Boolean, D>
which contains two partitions of the input elements according to aPredicate
, which are reduced according to the suppliedCollector
.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 elementsdownstream
- aCollector
implementing the downstream reduction- Returns:
- a
Map<Boolean, List<T>>
whichBoolean.TRUE
key is mapped to the result of downstreamCollector
collecting the the stream elements for which predicate is true andBoolean.FALSE
key is mapped to the result of downstreamCollector
collecting the other stream elements. - Since:
- 0.2.2
- See Also:
partitioningBy(Predicate)
,Collectors.partitioningBy(Predicate, Collector)
-
partitioningTo
public <C extends Collection<T>> Map<Boolean,C> partitioningTo(Predicate<? super T> predicate, Supplier<C> collectionFactory)
Returns aMap<Boolean, C>
which contains two partitions of the input elements according to aPredicate
.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 ofCollection
used as returnedMap
values.- Parameters:
predicate
- a predicate used for classifying input elementscollectionFactory
- a function which returns a new emptyCollection
which will be used to store the stream elements.- Returns:
- a
Map<Boolean, C>
whichBoolean.TRUE
key is mapped to the collection of the stream elements for which predicate is true andBoolean.FALSE
key is mapped to the collection of all other stream elements. - Since:
- 0.2.2
- See Also:
partitioningBy(Predicate, Collector)
,Collectors.partitioningBy(Predicate)
-
joining
public String joining()
Returns aString
which is the concatenation of the results of callingString.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 aString
which is the concatenation of the results of callingString.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 aString
which is the concatenation of the results of callingString.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 elementprefix
- the sequence of characters to be used at the beginning of the joined resultsuffix
- 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:
AbstractStreamEx.toArray(java.util.function.IntFunction)
-
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 which 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:
AbstractStreamEx.toArray(java.util.function.IntFunction)
-
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 collectionC
- the type of the resulting collection- Parameters:
mapper
- a non-interfering , stateless function to apply to each element which produces aCollection
of new valuessupplier
- 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 aList
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 theList
returned; if more control over the returnedList
is required, usetoFlatCollection(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 aCollection
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 aMap
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.- 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 toObject.equals(Object)
)- See Also:
Collectors.toMap(Function, Function)
,Collectors.toConcurrentMap(Function, Function)
,toMap(Function, Function)
-
toMap
public <K,V> Map<K,V> toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valMapper)
Returns aMap
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 functionV
- the output type of the value mapping function- Parameters:
keyMapper
- a mapping function to produce keysvalMapper
- 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 toObject.equals(Object)
)- See Also:
Collectors.toMap(Function, Function)
,Collectors.toConcurrentMap(Function, Function)
,toMap(Function)
-
toMap
public <K,V> Map<K,V> toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valMapper, BinaryOperator<V> mergeFunction)
Returns aMap
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 functionV
- the output type of the value mapping function- Parameters:
keyMapper
- a mapping function to produce keysvalMapper
- a mapping function to produce valuesmergeFunction
- a merge function, used to resolve collisions between values associated with the same key, as supplied toMap.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:
Collectors.toMap(Function, Function, BinaryOperator)
,Collectors.toConcurrentMap(Function, Function, BinaryOperator)
,toMap(Function, Function)
-
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)
orCollection.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 aSortedMap
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)
), anIllegalStateException
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:
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:
Collectors.toMap(Function, Function)
,Collectors.toConcurrentMap(Function, Function)
,toSortedMap(Function, Function)
,toNavigableMap(Function)
-
toSortedMap
public <K,V> SortedMap<K,V> toSortedMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valMapper)
Returns aSortedMap
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)
), anIllegalStateException
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 functionV
- the output type of the value mapping function- Parameters:
keyMapper
- a mapping function to produce keysvalMapper
- 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:
Collectors.toMap(Function, Function)
,Collectors.toConcurrentMap(Function, Function)
,toSortedMap(Function)
,toNavigableMap(Function, Function)
-
toSortedMap
public <K,V> SortedMap<K,V> toSortedMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valMapper, BinaryOperator<V> mergeFunction)
Returns aSortedMap
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 functionV
- the output type of the value mapping function- Parameters:
keyMapper
- a mapping function to produce keysvalMapper
- a mapping function to produce valuesmergeFunction
- a merge function, used to resolve collisions between values associated with the same key, as supplied toMap.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:
Collectors.toMap(Function, Function, BinaryOperator)
,toSortedMap(Function, Function)
,toNavigableMap(Function, Function, BinaryOperator)
-
toNavigableMap
public <V> NavigableMap<T,V> toNavigableMap(Function<? super T,? extends V> valMapper)
Returns aNavigableMap
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)
), anIllegalStateException
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:
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:
Collectors.toMap(Function, Function)
,Collectors.toConcurrentMap(Function, Function)
,toNavigableMap(Function, Function)
-
toNavigableMap
public <K,V> NavigableMap<K,V> toNavigableMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valMapper)
Returns aNavigableMap
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)
), anIllegalStateException
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 functionV
- the output type of the value mapping function- Parameters:
keyMapper
- a mapping function to produce keysvalMapper
- 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:
Collectors.toMap(Function, Function)
,Collectors.toConcurrentMap(Function, Function)
,toNavigableMap(Function)
-
toNavigableMap
public <K,V> NavigableMap<K,V> toNavigableMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends V> valMapper, BinaryOperator<V> mergeFunction)
Returns aNavigableMap
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 functionV
- the output type of the value mapping function- Parameters:
keyMapper
- a mapping function to produce keysvalMapper
- a mapping function to produce valuesmergeFunction
- a merge function, used to resolve collisions between values associated with the same key, as supplied toMap.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:
Collectors.toMap(Function, Function, BinaryOperator)
,Collectors.toConcurrentMap(Function, Function, BinaryOperator)
,toNavigableMap(Function, Function)
-
append
@SafeVarargs public final StreamEx<T> append(T... values)
Returns a newStreamEx
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 newStreamEx
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 newStreamEx
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 newStreamEx
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 newStreamEx
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 newStreamEx
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 which contents 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 which contents 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. Otherwisevalue.equals()
will be called to compare stream elements with the value.- Returns:
- true if this stream contains the specified value
- See Also:
Stream.anyMatch(Predicate)
-
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 (likenonNull()
works). Otherwisevalue.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(Object...)
,AbstractStreamEx.remove(Predicate)
-
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()
orcompareTo
forComparable
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:
without(Object)
,AbstractStreamEx.remove(Predicate)
-
reverseSorted
public StreamEx<T> reverseSorted()
Returns aStreamEx
consisting of the elements of this stream, sorted according to reverse natural order. If the elements of this stream are notComparable
, aClassCastException
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 suppliedCollector
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 streamA
- the intermediate accumulation type of theCollector
- 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
- aCollector
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 todistinct()
.- 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:
MoreCollectors.dominators(BiPredicate)
-
runLengths
public EntryStream<T,Long> runLengths()
Collapses adjacent equal elements and returns anEntryStream
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 asgroupingBy(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 usinggroupRuns(BiPredicate)
and map afterwards.- Returns:
- the new stream
- Since:
- 0.3.3
- See Also:
collapse(BiPredicate, BinaryOperator)
,groupRuns(BiPredicate)
-
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 the first element and every other element of this stream.This is a quasi-intermediate operation.
The size of the resulting stream is one element less than the input stream. If the input stream is empty or contains just one element, then the output stream will be empty.
- 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()
,headTail(BiFunction)
-
withFirst
public EntryStream<T,T> withFirst()
Creates anEntryStream
consisting of theMap.Entry
objects which keys are all the same and equal to the first element of this stream and values are the rest elements of this stream.This is a quasi-intermediate operation.
The size of the resulting stream is one element less than the input stream. If the input stream is empty or contains just one element, then the output stream will be empty.
- Returns:
- the new stream
- Since:
- 0.5.3
- See Also:
withFirst(BiFunction)
,headTail(BiFunction)
-
zipWith
public <V,R> StreamEx<R> zipWith(Stream<V> other, BiFunction<? super T,? super V,? extends R> mapper)
Creates a newStreamEx
which is the result of applying of the mapperBiFunction
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)
orzip(Object[], Object[], BiFunction)
respectively. If you want to zip the stream with the stream of indices, consider usingEntryStream.of(List)
instead.- Type Parameters:
V
- the type of the other stream elementsR
- the type of the resulting stream elements- Parameters:
other
- the stream to zip this stream withmapper
- 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(Stream)
-
zipWith
public <V,R> StreamEx<R> zipWith(BaseStream<V,?> other, BiFunction<? super T,? super V,? extends R> mapper)
Creates a newStreamEx
which is the result of applying of the mapperBiFunction
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)
orzip(Object[], Object[], BiFunction)
respectively. If you want to zip the stream with the stream of indices, consider usingEntryStream.of(List)
instead.- Type Parameters:
V
- the type of the other stream elementsR
- the type of the resulting stream elements- Parameters:
other
- the stream to zip this stream withmapper
- 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(BaseStream)
-
zipWith
public <V> EntryStream<T,V> zipWith(Stream<V> other)
Creates a newEntryStream
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)
orEntryStream.zip(Object[], Object[])
respectively. If you want to zip the stream with the stream of indices, consider usingEntryStream.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(Stream, BiFunction)
-
zipWith
public <V> EntryStream<T,V> zipWith(BaseStream<V,?> other)
Creates a newEntryStream
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)
orEntryStream.zip(Object[], Object[])
respectively. If you want to zip the stream with the stream of indices, consider usingEntryStream.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:
zipWith(BaseStream, BiFunction)
-
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 mapperBiFunction
to the first element of the current stream (head) and the stream containing the rest elements (tail). The mapper may returnnull
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)
andprepend(Object...)
operations, all of them are tail-stream optimized, so it will not fail withStackOverflowError
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)
ormapFirst(Function)
which parallelize better. Consider using these methods if its 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:
withFirst()
-
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 mapperBiFunction
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 returnnull
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()
, andprepend(Object...)
operations, both of them are tail-stream optimized, so it will not fail withStackOverflowError
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)
ormapFirst(Function)
which parallelize better. Consider using these methods if its 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:
headTail(BiFunction)
-
empty
public static <T> StreamEx<T> empty()
Returns an empty sequentialStreamEx
.- Type Parameters:
T
- the type of stream elements- Returns:
- an empty sequential stream
-
of
public static <T> StreamEx<T> of(T element)
Returns a sequentialStreamEx
containing a single element.- Type Parameters:
T
- the type of stream element- Parameters:
element
- the single element- Returns:
- a singleton sequential stream
- See Also:
Stream.of(Object)
-
of
@SafeVarargs public static <T> StreamEx<T> of(T... elements)
Returns a sequential orderedStreamEx
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:
Stream.of(Object...)
-
of
public static <T> StreamEx<T> of(T[] array, int startInclusive, int endExclusive)
Returns a sequentialStreamEx
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 usestartInclusive
- the first index to cover, inclusiveendExclusive
- index immediately past the last index to cover- Returns:
- a
StreamEx
for the array range - Throws:
ArrayIndexOutOfBoundsException
- ifstartInclusive
is negative,endExclusive
is less thanstartInclusive
, orendExclusive
is greater than the array size- Since:
- 0.1.1
- See Also:
Arrays.stream(Object[], int, int)
-
of
public static <T> StreamEx<T> of(Collection<? extends T> collection)
Returns a sequentialStreamEx
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:
Collection.stream()
-
ofReversed
public static <T> StreamEx<T> ofReversed(List<? extends T> list)
Returns a sequentialStreamEx
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 sequentialStreamEx
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 anStreamEx
object which wraps givenStream
.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 sequentialStreamEx
created from givenSpliterator
.- 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, orderedStreamEx
created from givenIterator
.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
orSpliterator
).- 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, orderedStreamEx
created from givenEnumeration
.Use this method only if you cannot provide better Stream source (like
Collection
orSpliterator
).- 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 sequentialStreamEx
containing anOptional
value, if present, otherwise returns an emptyStreamEx
.- 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 sequentialStreamEx
containing a single element, if non-null, otherwise returns an emptyStreamEx
.- 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 aStreamEx
, the elements of which are lines read from the suppliedBufferedReader
. TheStreamEx
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 underlyingBufferedReader
, it is wrapped in anUncheckedIOException
which will be thrown from theStreamEx
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 suppliedBufferedReader
- See Also:
BufferedReader.lines()
-
ofLines
public static StreamEx<String> ofLines(Reader reader)
Returns aStreamEx
, the elements of which are lines read from the suppliedReader
. TheStreamEx
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 underlyingReader
, it is wrapped in anUncheckedIOException
which will be thrown from theStreamEx
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 suppliedReader
- See Also:
ofLines(BufferedReader)
-
ofLines
public static StreamEx<String> ofLines(Path path) throws IOException
Read all lines from a file as aStreamEx
. Bytes from the file are decoded into characters using theUTF-8
charset
and the same line terminators as specified byFiles.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 theStreamEx
method that caused the read to take place. In case anIOException
is thrown when closing the file, it is also wrapped as anUncheckedIOException
.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'sclose
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:
Files.lines(Path)
-
ofLines
public static StreamEx<String> ofLines(Path path, Charset charset) throws IOException
Read all lines from a file as aStreamEx
.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 theStreamEx
method that caused the read to take place. In case anIOException
is thrown when closing the file, it is also wrapped as anUncheckedIOException
.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'sclose
method is invoked after the stream operations are completed.- Parameters:
path
- the path to the filecharset
- 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:
Files.lines(Path, Charset)
-
ofKeys
public static <T> StreamEx<T> ofKeys(Map<T,?> map)
Returns a sequentialStreamEx
with keySet of givenMap
as its source.- Type Parameters:
T
- the type of map keys- Parameters:
map
- input map- Returns:
- a sequential
StreamEx
over the keys of givenMap
- Throws:
NullPointerException
- if map is null- See Also:
Map.keySet()
-
ofKeys
public static <T,V> StreamEx<T> ofKeys(Map<T,V> map, Predicate<? super V> valueFilter)
Returns a sequentialStreamEx
of givenMap
keys which corresponding values match the supplied filter.- Type Parameters:
T
- the type of map keys and created stream elementsV
- the type of map values- Parameters:
map
- input mapvalueFilter
- a predicate used to test values- Returns:
- a sequential
StreamEx
over the keys of givenMap
which corresponding values match the supplied filter. - Throws:
NullPointerException
- if map is null- See Also:
Map.keySet()
-
ofValues
public static <T> StreamEx<T> ofValues(Map<?,T> map)
Returns a sequentialStreamEx
with values of givenMap
as its source.- Type Parameters:
T
- the type of map keys- Parameters:
map
- input map- Returns:
- a sequential
StreamEx
over the values of givenMap
- Throws:
NullPointerException
- if map is null- See Also:
Map.values()
-
ofValues
public static <K,T> StreamEx<T> ofValues(Map<K,T> map, Predicate<? super K> keyFilter)
Returns a sequentialStreamEx
of givenMap
values which corresponding keys match the supplied filter.- Type Parameters:
K
- the type of map keysT
- the type of map values and created stream elements- Parameters:
map
- input mapkeyFilter
- a predicate used to test keys- Returns:
- a sequential
StreamEx
over the values of givenMap
which corresponding keys match the supplied filter. - Throws:
NullPointerException
- if map is null- See Also:
Map.values()
-
ofPermutations
public static StreamEx<int[]> ofPermutations(int length)
Returns a newStreamEx
ofint[]
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 exceedLong.MAX_VALUE
.- Returns:
- new sequential
StreamEx
of possible permutations. - Throws:
IllegalArgumentException
- if length is negative or number of possible permutations exceedsLong.MAX_VALUE
.- Since:
- 0.2.2
-
ofCombinations
public static StreamEx<int[]> ofCombinations(int n, int k)
Returns a newStreamEx
ofint[]
arrays containing all the possible combinations of lengthk
consisting of numbers from 0 ton-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 elementsk
- number of elements in each combination- Returns:
- new sequential stream of possible combinations. Returns an empty stream if
k
is bigger thann
. - Throws:
IllegalArgumentException
- if n or k is negative or number of possible combinations exceedsLong.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 splitpattern
- The pattern to use for splitting- Returns:
- The stream of strings computed by splitting the input around matches of this pattern
- See Also:
Pattern.splitAsStream(CharSequence)
-
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 splitregex
- 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:
Pattern.splitAsStream(CharSequence)
,split(CharSequence, char)
-
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 splitdelimiter
- 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:
Pattern.splitAsStream(CharSequence)
-
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 splitdelimiter
- The delimiter character to use for splittingtrimEmpty
- 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:
Pattern.splitAsStream(CharSequence)
-
iterate
public static <T> StreamEx<T> iterate(T seed, UnaryOperator<T> f)
Returns an infinite sequential orderedStreamEx
produced by iterative application of a functionf
to an initial elementseed
, producing aStreamEx
consisting ofseed
,f(seed)
,f(f(seed))
, etc.The first element (position
0
) in theStreamEx
will be the providedseed
. Forn > 0
, the element at positionn
, will be the result of applying the functionf
to the element at positionn - 1
.- Type Parameters:
T
- the type of stream elements- Parameters:
seed
- the initial elementf
- a function to be applied to to the previous element to produce a new element- Returns:
- a new sequential
StreamEx
- See Also:
iterate(Object, Predicate, UnaryOperator)
-
iterate
public static <T> StreamEx<T> iterate(T seed, Predicate<? super T> predicate, UnaryOperator<T> f)
Returns a sequential orderedStreamEx
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 elementpredicate
- 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:
iterate(Object, UnaryOperator)
-
generate
public static <T> StreamEx<T> generate(Supplier<T> s)
Returns an infinite sequential unorderedStreamEx
where each element is generated by the providedSupplier
. This is suitable for generating constant streams, streams of random elements, etc.- Type Parameters:
T
- the type of stream elements- Parameters:
s
- theSupplier
of generated elements- Returns:
- a new infinite sequential unordered
StreamEx
- See Also:
Stream.generate(Supplier)
,EntryStream.generate(Supplier, Supplier)
-
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 it 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 unorderedStreamEx
of given length which elements are equal to supplied value.- Type Parameters:
T
- the type of stream elements- Parameters:
value
- the constant valuelength
- 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 orderedStreamEx
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))
andmapper.apply(list.get(1), list.get(2))
. The number of elements in the resulting stream islist.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 elementsT
- type of the stream elements- Parameters:
list
- a list to take the elements frommapper
- a non-interfering, stateless function to apply to each pair of list elements.- Returns:
- a new
StreamEx
- Since:
- 0.3.6
- See Also:
EntryStream.ofPairs(List)
-
ofPairs
public static <U,T> StreamEx<T> ofPairs(U[] array, BiFunction<? super U,? super U,? extends T> mapper)
Returns a sequential orderedStreamEx
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])
andmapper.apply(array[1], array[2])
. The number of elements in the resulting stream isarray.length*(array.length+1L)/2
.- Type Parameters:
U
- type of the array elementsT
- type of the stream elements- Parameters:
array
- an array to take the elements frommapper
- a non-interfering, stateless function to apply to each pair of array elements.- Returns:
- a new
StreamEx
- Since:
- 0.3.6
- See Also:
EntryStream.ofPairs(Object[])
-
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 sequentialStreamEx
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 elementsV
- the type of the second list elementsT
- the type of the resulting stream elements- Parameters:
first
- the first list, assumed to be unmodified during usesecond
- the second list, assumed to be unmodified during usemapper
- 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:
EntryStream.zip(List, List)
-
zip
public static <U,V,T> StreamEx<T> zip(U[] first, V[] second, BiFunction<? super U,? super V,? extends T> mapper)
Returns a sequentialStreamEx
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 elementsV
- the type of the second array elementsT
- the type of the resulting stream elements- Parameters:
first
- the first arraysecond
- the second arraymapper
- 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:
EntryStream.zip(Object[], Object[])
-
ofTree
public static <T> StreamEx<T> ofTree(T root, Function<T,Stream<T>> mapper)
Return a newStreamEx
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 theclose()
method of the resulting stream returned byofTree()
.- Type Parameters:
T
- the type of tree nodes- Parameters:
root
- root node of the treemapper
- 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:
EntryStream.ofTree(Object, BiFunction)
,ofTree(Object, Class, Function)
-
ofTree
public static <T,TT extends T> StreamEx<T> ofTree(T root, Class<TT> collectionClass, Function<TT,Stream<T>> mapper)
Return a newStreamEx
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 theclose()
method of the resulting stream returned byofTree()
.- Type Parameters:
T
- the base type of tree nodesTT
- the sub-type of composite tree nodes which may have children- Parameters:
root
- root node of the treecollectionClass
- a class representing the composite tree nodemapper
- 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:
EntryStream.ofTree(Object, Class, BiFunction)
,ofTree(Object, Function)
-
ofSubLists
public static <T> StreamEx<List<T>> ofSubLists(List<T> source, int length)
Returns a newStreamEx
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 listlength
- 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(List, int, int)
,List.subList(int, int)
-
ofSubLists
public static <T> StreamEx<List<T>> ofSubLists(List<T> source, int length, int shift)
Returns a newStreamEx
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 listlength
- 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:
List.subList(int, int)
-
cartesianProduct
public static <T> StreamEx<List<T>> cartesianProduct(Collection<? extends Collection<T>> source)
Returns a newStreamEx
which elements areList
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:
cartesianPower(int, Collection)
-
cartesianProduct
public static <T,U> StreamEx<U> cartesianProduct(Collection<? extends Collection<T>> source, U identity, BiFunction<U,? super T,U> accumulator)
Returns a newStreamEx
which elements are results of reduction of all possible tuples composed from 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 elementsU
- 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 valueaccumulator
- 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:
cartesianProduct(Collection)
,cartesianPower(int, Collection, Object, BiFunction)
-
cartesianPower
public static <T> StreamEx<List<T>> cartesianPower(int n, Collection<T> source)
Returns a newStreamEx
which elements areList
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 theList
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:
cartesianProduct(Collection)
-
cartesianPower
public static <T,U> StreamEx<U> cartesianPower(int n, Collection<T> source, U identity, BiFunction<U,? super T,U> accumulator)
Returns a newStreamEx
which elements are results of reduction of all possible n-tuples composed from 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 elementsU
- 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 valueaccumulator
- 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:
cartesianProduct(Collection, Object, BiFunction)
,cartesianPower(int, Collection)
-
spliterator
public Spliterator<T> spliterator()
- Specified by:
spliterator
in interfaceBaseStream<T,S extends BaseStream<T,S>>
-
isParallel
public boolean isParallel()
- Specified by:
isParallel
in interfaceBaseStream<T,S extends BaseStream<T,S>>
-
close
public void close()
- Specified by:
close
in interfaceAutoCloseable
- Specified by:
close
in interfaceBaseStream<T,S extends BaseStream<T,S>>
-
-