Class BiStream<K,V>
- All Implemented Interfaces:
AutoCloseable
Stream
, but operating over a sequence of pairs of objects.
Note: For ease of reference, this class uses 'key' and 'value' to refer to each of the two parts of each pair in the sequence. However, both 'key' and 'value' can be any object of the appropriate type, or null. There is no implication that keys or key-value pairs are unique, or that keys can be compared for equality. You may equivalently read them as 'left' and 'right', or 'first' and 'second'.
If the contents of the stream aren't identifiably 'keys' or 'values', and the methods with 'key' or 'value' in their name are distracting, consider using the pair-wise operations. For instance, instead of:
BiStream.from(cities.stream(), City::population, City::latitude)
.filterKeys(p -> p > 10000);
you might use:
BiStream.from(cities.stream(), City::population, City::latitude)
.filter((population, lat) -> population > 10000);
Keys and values are allowed to be null by default unless explicitly documented otherwise.
Some methods (e.g. mapKeys()
) come in two versions, one taking BiFunction
(which will receive both key and value) and another taking Function
(which in this case
will receive only the key) . They operate equivalently otherwise.
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic final class
Builder forBiStream
.static interface
A predicate used to partition aBiStream
into sub-groups of consecutive pairs. -
Method Summary
Modifier and TypeMethodDescriptionabstract boolean
allMatch
(BiPredicate<? super K, ? super V> predicate) Returns true if all pairs in this stream matchpredicate
.abstract boolean
anyMatch
(BiPredicate<? super K, ? super V> predicate) Returns true if any pair in this stream matchespredicate
.Returns aBiStream
consisting of the pairs in this stream, followed by the pairs inother
.Returns aBiStream
consisting of the pairs in this stream, followed by the pair ofkey
andvalue
.static <K,
V> BiStream <K, V> biStream
(Collection<K> keys, Function<? super K, ? extends V> toValue) Returns aBiStream
of mappings betweenkeys
and the corresponding return values of thetoValue
function.static <T> BiStream
<T, T> biStream
(Collection<T> elements) Short-hand forfrom(elements, identity(), identity())
.static <K,
V> BiStream <K, V> biStream
(Function<? super V, ? extends K> toKey, Collection<V> values) Returns aBiStream
of mappings between the key returned by thetoKey
function (when applied to each element ofvalues
), and the element itself.static <K,
V> BiStream <K, V> Returns aBiStream
of mappings between the key returned by thetoKey
function (when applied to each element ofvalues
), and the element itself.static <K,
V> BiStream <K, V> Returns aBiStream
of mappings betweenkeys
and the corresponding return values of thetoValue
function.static <T> BiStream
<T, T> Short-hand forfrom(elements, identity(), identity())
.static <K,
V> BiStream.Builder <K, V> builder()
Returns a newBiStream.Builder
.abstract void
close()
Closes any resources associated with this stream, typically used in a try-with-resources statement.abstract <A> A
collect
(A container, BiAccumulator<? super A, ? super K, ? super V> accumulator) Performs mutable reduction, as incollect(ImmutableMap.builder(), ImmutableMap.Builder::put)
.abstract <R> R
collect
(BiCollector<? super K, ? super V, R> collector) Returns an object of typeR
that is the result of collecting the pairs in this stream usingcollector
.final <T,
R> R collect
(BiCollector<? super K, ? super V, T> collector, Function<? super T, R> finisher) Equivalent tocollect(collectingAndThen(collector, finisher))
but helps to save syntactic noise.static <K,
V> BiStream <K, V> concat
(BiStream<? extends K, ? extends V> s1, BiStream<? extends K, ? extends V> s2, BiStream<? extends K, ? extends V>... rest) Returns aBiStream
of the entries froms1
,s2
thenrest
in encounter order.static <K,
V> BiStream <K, V> concat
(Map<? extends K, ? extends V> m1, Map<? extends K, ? extends V> m2, Map<? extends K, ? extends V>... rest) Returns aBiStream
of the entries fromm1
,m2
thenrest
in encounter order.static <K,
V> BiStream <K, V> Returns aBiStream
of pairs frombiStreams
concatenated in encounter order.concatenating
(Function<? super T, ? extends BiStream<? extends K, ? extends V>> toBiStream) Returns aCollector
that concatenatesBiStream
objects derived from the input elements using the giventoBiStream
function.final long
count()
Returns the count of pairs in this stream.crossJoining
(Stream<R> right) Returns aCollector
that will pair each input element with each element fromright
into a newBiStream
.distinct()
Returns aBiStream
consisting of only the distinct pairs (according toObject.equals(Object)
for both key and value).static <K,
V> BiStream <K, V> empty()
Returns an emptyBiStream
.filter
(BiPredicate<? super K, ? super V> predicate) Filter this stream to only pairs matchingpredicate
.filterKeys
(Predicate<? super K> predicate) Filter this stream to only pairs whose key matchespredicate
.filterValues
(Predicate<? super V> predicate) Filter this stream to only pairs whose value matchespredicate
.final BiOptional
<K, V> findAny()
Returns any pair from this stream, orBiOptional.empty()
if the stream is empty.final BiOptional
<K, V> Returns the first pair from this stream, orBiOptional.empty()
if the stream is empty.final <K2,
V2> BiStream <K2, V2> flatMap
(BiFunction<? super K, ? super V, ? extends BiStream<? extends K2, ? extends V2>> mapper) Maps each pair in this stream to zero or more pairs in anotherBiStream
.flatMapKeys
(BiFunction<? super K, ? super V, ? extends Stream<? extends K2>> keyMapper) Maps each key to zero or more keys of typeK2
.flatMapKeys
(Function<? super K, ? extends Stream<? extends K2>> keyMapper) Maps each key to zero or more keys of typeK2
.final DoubleStream
flatMapToDouble
(BiFunction<? super K, ? super V, ? extends DoubleStream> mapper) Maps a single pair to zero or moredouble
s.final IntStream
flatMapToInt
(BiFunction<? super K, ? super V, ? extends IntStream> mapper) Maps a single pair to zero or moreint
s.final LongStream
flatMapToLong
(BiFunction<? super K, ? super V, ? extends LongStream> mapper) Maps a single pair to zero or morelong
s.final <T> Stream
<T> flatMapToObj
(BiFunction<? super K, ? super V, ? extends Stream<? extends T>> mapper) Maps a single pair to zero or more objects of typeT
.flatMapValues
(BiFunction<? super K, ? super V, ? extends Stream<? extends V2>> valueMapper) Maps each value to zero or more values of typeV2
.flatMapValues
(Function<? super V, ? extends Stream<? extends V2>> valueMapper) Maps each value to zero or more values of typeV2
.abstract void
forEach
(BiConsumer<? super K, ? super V> action) Performsaction
for each pair in this stream.abstract void
forEachOrdered
(BiConsumer<? super K, ? super V> consumer) Performsaction
for each pair in this stream, in order.static <K,
V> BiStream <K, V> from
(Collection<? extends Map.Entry<? extends K, ? extends V>> entries) Returns aBiStream
of the key value pairs fromentries
.static <T,
K, V> BiStream <K, V> from
(Collection<T> elements, Function<? super T, ? extends K> toKey, Function<? super T, ? extends V> toValue) Deprecated.static <K,
V> BiStream <K, V> Returns aBiStream
of the entries inmap
.static <K,
V> BiStream <K, V> Returns aBiStream
of the pairs fromstream
.static <T,
K, V> BiStream <K, V> from
(Stream<T> stream, Function<? super T, ? extends K> toKey, Function<? super T, ? extends V> toValue) Deprecated.UsebiStream(User::id, users)
to createBiStream<UserId, User>
, or, usebiStream(users, User::getAccount)
to createBiStream<User, Account>
.fromEntries
(Stream<E> entryStream) final <G,
A, R> BiStream <G, R> groupConsecutiveBy
(BiFunction<? super K, ? super V, ? extends G> classifier, BiCollector<? super K, ? super V, R> groupCollector) Returns aBiStream
consisting of consecutive groupings from this stream.groupConsecutiveBy
(Function<? super K, ? extends G> classifier, BinaryOperator<V> groupReducer) Returns a lazyBiStream
of the consecutive groups of pairs from this stream.final <G,
A, R> BiStream <G, R> groupConsecutiveBy
(Function<? super K, ? extends G> classifier, Collector<? super V, A, ? extends R> groupCollector) Returns aBiStream
consisting of consecutive groupings from this stream.final <R> Stream
<R> groupConsecutiveIf
(BiStream.Partitioner<? super K, ? super V> sameGroup, BiCollector<? super K, ? super V, R> groupCollector) Returns a lazyStream
of the consecutive groups of values from this stream.groupConsecutiveIf
(BiPredicate<? super K, ? super K> sameGroup, BinaryOperator<V> groupReducer) Returns a lazyStream
of the consecutive groups of values from this stream.final <A,
R> Stream <R> groupConsecutiveIf
(BiPredicate<? super K, ? super K> sameGroup, Collector<? super V, A, R> groupCollector) Returns a lazyStream
of the consecutive groups of values from this stream.groupingBy
(Function<? super T, ? extends K> classifier) Returns aCollector
that groups the input elements byclassifier
and collects the values mapping to the same key into aList
.groupingBy
(Function<? super T, ? extends K> classifier, Function<? super T, ? extends V> mapper, BinaryOperator<V> reducer) Returns aCollector
that groups the input elements byclassifier
and reduces the values mapping to the same key usingmapper
thenreducer
.groupingBy
(Function<? super T, ? extends K> classifier, Collector<? super T, ?, V> valueCollector) Returns aCollector
that groups the input elements byclassifier
and collects the values mapping to the same key usingvalueCollector
.groupingBy
(Function<? super V, ? extends K> classifier, BinaryOperator<V> reducer) Returns aCollector
that groups the input elements byclassifier
and reduces the values mapping to the same key usingreducer
.groupingByEach
(Function<? super T, ? extends Stream<? extends K>> keysFunction, Function<? super T, ? extends V> valueFunction, BinaryOperator<V> groupReducer) Returns aCollector
grouping input elements by each of the multiple keys returned by thekeysFunction
.groupingByEach
(Function<? super T, ? extends Stream<? extends K>> keysFunction, Function<? super T, ? extends V> valueFunction, Collector<V, ?, G> groupCollector) Returns aCollector
grouping input elements by each of the multiple keys returned by thekeysFunction
.groupingByEach
(Function<? super T, ? extends Stream<? extends K>> keysFunction, Collector<T, ?, V> groupCollector) Returns aCollector
grouping input elements by each of the multiple keys returned by thekeysFunction
.inverse()
Returns aBiStream
where each pair is a pair from this stream with the key and value swapped.keys()
Returns aStream
consisting of only the keys from each pair in this stream.limit
(int maxSize) Returns aBiStream
consisting of the only the firstmaxSize
pairs of this stream.final <K2,
V2> BiStream <K2, V2> map
(BiFunction<? super K, ? super V, ? extends Both<? extends K2, ? extends V2>> mapper) Returns aBiStream
consisting of the result pairs of applyingmapper
to the pairs in thisBiStream
.<K2,
V2> BiStream <K2, V2> map
(BiFunction<? super K, ? super V, ? extends K2> keyMapper, BiFunction<? super K, ? super V, ? extends V2> valueMapper) Returns aBiStream
consisting of the results of applyingkeyMapper
andvalueMapper
to the pairs in thisBiStream
.final <K2,
V2> BiStream <K2, V2> mapIfPresent
(BiFunction<? super K, ? super V, ? extends BiOptional<? extends K2, ? extends V2>> mapper) Returns aBiStream
consisting of the results of applyingmapper
function to the pairs in thisBiStream
.mapKeys
(BiFunction<? super K, ? super V, ? extends K2> keyMapper) Returns aBiStream
of pairs whose keys are the result of applyingkeyMapper
to the key of each pair in thisBiStream
, and whose values are unchanged.Maps each key to another key of typeK2
.mapKeysIfPresent
(BiFunction<? super K, ? super V, ? extends Optional<? extends K2>> keyMapper) Returns aBiStream
of pairs whose keys are the result of applyingkeyMapper
to each pair in thisBiStream
, and whose values are unchanged.mapKeysIfPresent
(Function<? super K, ? extends Optional<? extends K2>> keyMapper) Returns aBiStream
of pairs whose keys are the result of applyingkeyMapper
to the key of each pair in thisBiStream
, and whose values are unchanged.mapKeysIfPresent
(Map<? super K, ? extends K2> keyMapping) GivenkeyMapping
that maps the keys of typeK
to elements of typeK2
, returns aBiStream
of type<K2, V>
.abstract DoubleStream
mapToDouble
(ToDoubleBiFunction<? super K, ? super V> mapper) abstract IntStream
mapToInt
(ToIntBiFunction<? super K, ? super V> mapper) abstract LongStream
mapToLong
(ToLongBiFunction<? super K, ? super V> mapper) abstract <T> Stream
<T> mapToObj
(BiFunction<? super K, ? super V, ? extends T> mapper) Returns aStream
consisting of the results of applyingmapper
to each pair in thisBiStream
.final <T> Stream
<T> mapToObjIfPresent
(BiFunction<? super K, ? super V, ? extends Optional<? extends T>> mapper) Returns aStream
consisting of the results of applyingmapper
to each pair in thisBiStream
.mapValues
(BiFunction<? super K, ? super V, ? extends V2> valueMapper) Maps each value to another value of typeV2
.Maps each value to another value of typeV2
.mapValuesIfPresent
(BiFunction<? super K, ? super V, ? extends Optional<? extends V2>> valueMapper) Returns aBiStream
of pairs whose values are the result of applyingvalueMapper
to each pair in thisBiStream
, and whose keys are unchanged.mapValuesIfPresent
(Function<? super V, ? extends Optional<? extends V2>> valueMapper) Returns aBiStream
of pairs whose values are the result of applyingvalueMapper
to the value of each pair in thisBiStream
, and whose keys are unchanged.mapValuesIfPresent
(Map<? super V, ? extends V2> valueMapping) GivenvalueMapping
that maps values of typeV
to result values of typeV2
, returns aBiStream
of type<K, V2>
.final boolean
noneMatch
(BiPredicate<? super K, ? super V> predicate) Returns true if no pairs in this stream matchpredicate
.static <K,
V> BiStream <K, V> of
(K key, V value) Returns aBiStream
of a single pair containingkey
andvalue
.static <K,
V> BiStream <K, V> of
(K k1, V v1, K k2, V v2) Returns aBiStream
of two pairs, containing the supplied keys and values.static <K,
V> BiStream <K, V> of
(K k1, V v1, K k2, V v2, K k3, V v3) Returns aBiStream
of three pairs, containing the supplied keys and values.static <K,
V> BiStream <K, V> of
(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) Returns aBiStream
of 4 pairs, containing the supplied keys and values.static <K,
V> BiStream <K, V> of
(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) Returns aBiStream
of 5 pairs, containing the supplied keys and values.static <K,
V> BiStream <K, V> of
(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) Returns aBiStream
of 6 pairs, containing the supplied keys and values.static <K,
V> BiStream <K, V> of
(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) Returns aBiStream
of 7 pairs, containing the supplied keys and values.static <K,
V> BiStream <K, V> of
(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8) Returns aBiStream
of 8 pairs, containing the supplied keys and values.static <K,
V> BiStream <K, V> of
(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9) Returns aBiStream
of 9 pairs, containing the supplied keys and values.static <K,
V> BiStream <K, V> of
(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10) Returns aBiStream
of 10 pairs, containing the supplied keys and values.peek
(BiConsumer<? super K, ? super V> action) Returns aBiStream
consisting of the pairs of this stream, additionally invokingaction
on each pair as pairs are consumed from the resulting stream.static <I,
O> BiStream <I, O> repeat
(Function<? super I, ? extends O> work, I initial, BiFunction<? super I, ? super O, ? extends Optional<? extends I>> increment) Returns a stream of the inputs and outputs from repeated applications of thework
function.skip
(int n) Returns aBiStream
consisting of the remaining pairs from this stream, after discarding the firstn
pairs.skipIf
(BiPredicate<? super K, ? super V> predicate) Filter this stream to exclude pairs matchingpredicate
.skipKeysIf
(Predicate<? super K> predicate) Filter this stream to exclude pairs whose key matchespredicate
.skipValuesIf
(Predicate<? super V> predicate) Filter this stream to exclude pairs whose value matchespredicate
.sorted
(Comparator<? super K> byKey, Comparator<? super V> byValue) Returns aBiStream
consisting of the pairs in this stream, in the order produced by applying thebyKey
comparator on the keys of each pair, and then thebyValue
comparator on the values of pairs with equal keys.sortedBy
(BiFunction<? super K, ? super V, T> sortKeyFunction, Comparator<? super T> comparator) Returns aBiStream
consisting of the pairs in this stream, in the order produced by applyingcomparator
on the result of applying thesortKeyFunction
.sortedByKeys
(Comparator<? super K> comparator) Returns aBiStream
consisting of the pairs in this stream, in the order produced by applyingcomparator
on the keys of each pair.sortedByValues
(Comparator<? super V> comparator) Returns aBiStream
consisting of the pairs in this stream, in the order produced by applyingcomparator
on the values of each pair.Returns aCollector
that accumulates every neighboring pair of elements into a newBiStream
.Returns aCollector
that copies each input element as a pair of itself into an equivalentBiStream
.toBiStream
(Function<? super E, ? extends Both<? extends K, ? extends V>> toPair) Returns aCollector
that splits each input element as a pair and collects them into aBiStream
.toBiStream
(Function<? super E, ? extends K> toKey, Function<? super E, ? extends V> toValue) Returns aCollector
that splits each input element as a pair and collects them into aBiStream
.toMap()
Returns an immutableMap
that is the result of collecting the pairs in this stream.values()
Returns aStream
consisting of only the values from each pair in this stream.static <L,
R> BiStream <L, R> zip
(Collection<L> left, Collection<R> right) Returns aBiStream
in which the first element inleft
is paired with the first element inright
; the second paired with the corresponding second and the third with the corresponding third etc.static <L,
R> BiStream <L, R> Returns aBiStream
in which the first element inleft
is paired with the first element inright
; the second paired with the corresponding second and the third with the corresponding third etc.
-
Method Details
-
builder
Returns a newBiStream.Builder
.- Since:
- 3.2
-
groupingBy
public static <K,V> Collector<V,?, groupingByBiStream<K, V>> (Function<? super V, ? extends K> classifier, BinaryOperator<V> reducer) Returns aCollector
that groups the input elements byclassifier
and reduces the values mapping to the same key usingreducer
.ImmutableMap<CurrencyCode, Money> expenseByCurrency = expenses.stream() .collect(groupingBy(Money::currencyCode, Money::add)) .collect(ImmutableMap::toImmutableMap);
Entries are collected in encounter order.
- Since:
- 3.3
-
groupingBy
public static <T,K, Collector<T,V> ?, groupingByBiStream<K, V>> (Function<? super T, ? extends K> classifier, Function<? super T, ? extends V> mapper, BinaryOperator<V> reducer) Returns aCollector
that groups the input elements byclassifier
and reduces the values mapping to the same key usingmapper
thenreducer
.ImmutableMap<State, Money> householdIncomeByState = households.stream() .collect(groupingBy(Household::state, Household::income, Money::add)) .collect(ImmutableMap::toImmutableMap);
Entries are collected in encounter order.
- Since:
- 3.3
-
groupingBy
public static <T,K> Collector<T,?, groupingByBiStream<K, List<T>>> (Function<? super T, ? extends K> classifier) Returns aCollector
that groups the input elements byclassifier
and collects the values mapping to the same key into aList
. Similar but different fromCollectors.groupingBy(Function)
, this method collects the groups intoBiStream()
instead, allowing fluent method chaining. For example:
Even if you don't need to chain more methods, using this collector allows you to fluently collect the results into the desired container type. For exampleMap<EmployeeId, List<Task>> employeesWithMultipleTasks = tasks.stream() .collect(BiStream.groupingBy(Task::assignedTo)) .filterValues(tasks -> tasks.size() > 1) .toMap();
toMap()
collects to an immutableMap
; orcollect(Collectors::toConcurrentMap)
if concurrency is needed.Entries are collected in encounter order.
- Since:
- 3.0
-
groupingBy
public static <T,K, Collector<T,V> ?, groupingByBiStream<K, V>> (Function<? super T, ? extends K> classifier, Collector<? super T, ?, V> valueCollector) Returns aCollector
that groups the input elements byclassifier
and collects the values mapping to the same key usingvalueCollector
. Similar but different fromCollectors.groupingBy(Function, Collector)
, this method collects the groups intoBiStream()
instead, allowing fluent method chaining. For example:
Even if you don't need to chain more methods, using this collector allows you to fluently collect the results into the desired container type. For exampleMap<EmployeeId, Integer> topTenEmployeesByWorkHour = projects.stream() .flatMap(project -> project.getMembers().stream()) // Stream<TeamMember> .collect(BiStream.groupingBy(TeamMember::employeeId, summingInt(TeamMember::hours))) .sortedByValues(Comparator.reverseOrder()) .limit(10) .toMap();
toMap()
collects to an immutableMap
; or you could supplycollect(ImmutableBiMap::toImmutableBiMap)
ifBiMap
is needed.Entries are collected in encounter order.
- Since:
- 3.0
-
groupingByEach
public static <T,K, Collector<T,V> ?, groupingByEachBiStream<K, V>> (Function<? super T, ? extends Stream<? extends K>> keysFunction, Collector<T, ?, V> groupCollector) Returns aCollector
grouping input elements by each of the multiple keys returned by thekeysFunction
. It's similar togroupingBy(Function, Collector)
except each element can belong to multiple groups. For example:ImmutableMap<Person, ImmutableList<Club>> clubMemberships = clubs.stream() .collect( groupingByEach(club -> club.getMembers().stream(), toImmutableList())) .toMap();
Entries are collected in encounter order.
- Since:
- 6.5
-
groupingByEach
public static <T,K, Collector<T,V, G> ?, groupingByEachBiStream<K, G>> (Function<? super T, ? extends Stream<? extends K>> keysFunction, Function<? super T, ? extends V> valueFunction, Collector<V, ?, G> groupCollector) Returns aCollector
grouping input elements by each of the multiple keys returned by thekeysFunction
. The input element is passed to thevalueFunction
and the return value is added to every group it belongs to. And finally each group is collected usinggroupCollector
. For example:ImmutableMap<EmployeeId, ImmutableList<ProjectId>> projectIdsPerEmployee = projects.stream() .collect( groupingByEach( project -> project.getOwnersList().stream(), Project::id, toImmutableList())) .toMap();
Entries are collected in encounter order.
- Since:
- 6.5
-
groupingByEach
public static <T,K, Collector<T,V> ?, groupingByEachBiStream<K, V>> (Function<? super T, ? extends Stream<? extends K>> keysFunction, Function<? super T, ? extends V> valueFunction, BinaryOperator<V> groupReducer) Returns aCollector
grouping input elements by each of the multiple keys returned by thekeysFunction
. It's similar togroupingBy(Function, Function, BinaryOperator)
except each element can belong to multiple groups. For example:ImmutableMap<Person, Money> clubMembershipFees = clubs.stream() .collect( groupingByEach( club -> club.getMembers().stream(), Club::getMembershipFee, Money::add)) .toMap();
Entries are collected in encounter order.
- Since:
- 6.5
-
concatenating
public static <T,K, Collector<T,V> ?, concatenatingBiStream<K, V>> (Function<? super T, ? extends BiStream<? extends K, ? extends V>> toBiStream) Returns aCollector
that concatenatesBiStream
objects derived from the input elements using the giventoBiStream
function.For example:
Map<EmployeeId, Task> billableTaskAssignments = projects.stream() .collect(concatenating(p -> BiStream.from(p.getTaskAssignments()))) .filterValues(Task::billable) .toMap();
- Since:
- 3.0
-
crossJoining
Returns aCollector
that will pair each input element with each element fromright
into a newBiStream
. For example:ImmutableList<QuarterlyReport> allQuarterlyReports = quarters.stream() .collect(crossJoining(departments)) .mapToObj(QuarterlyReport::new) .collect(toImmutableList());
The input elements are repeated once per element from
right
. For example:[1, 2, 3].collect(crossJoining([a, b]))
will generate[{1, a}, {2, a}, {3, a}, {1, b}, {2, b}, {3, b}]
.The returned
BiStream
takesO(n)
space wheren
is the size of the input elements. The "cross-joining" with theright
stream is computed on-the-fly withO(1)
memory cost.- Since:
- 3.0
-
toAdjacentPairs
Returns aCollector
that accumulates every neighboring pair of elements into a newBiStream
. For exampleStream.of(1, 2, 3, 4).collect(toAdjacentPairs())
will return[{1, 2}, {2, 3}, {3, 4}]
.If the input has 0 or 1 elements then the output is an empty
BiStream
. Otherwise the length of the outputBiStream
is one less than the length of the input.- Since:
- 3.2
-
toBiStream
public static <E,K, Collector<E,V> ?, toBiStreamBiStream<K, V>> (Function<? super E, ? extends K> toKey, Function<? super E, ? extends V> toValue) Returns aCollector
that splits each input element as a pair and collects them into aBiStream
.Note that it's more efficient to use
BiStream.from(stream, toKey, toValue)
thanstream.collect(toBiStream(toKey, toValue))
. The latter is intended to be used in the middle of a long stream pipeline, when performance isn't critical.- Since:
- 3.2
-
toBiStream
public static <E,K, Collector<E,V> ?, toBiStreamBiStream<K, V>> (Function<? super E, ? extends Both<? extends K, ? extends V>> toPair) Returns aCollector
that splits each input element as a pair and collects them into aBiStream
.Note that it's more efficient to use
BiStream.from(stream, toPair)
thanstream.collect(toBiStream(toPair))
. The latter is intended to be used in the middle of a long stream pipeline, when performance isn't critical.- Since:
- 5.1
-
toBiStream
Returns aCollector
that copies each input element as a pair of itself into an equivalentBiStream
.Note that it's more efficient to use
biStream(stream)
thanstream.collect(toBiStream())
. The latter is intended to be used in the middle of a long stream pipeline, when performance isn't critical.- Since:
- 3.6
-
empty
Returns an emptyBiStream
. -
of
Returns aBiStream
of a single pair containingkey
andvalue
. -
of
Returns aBiStream
of two pairs, containing the supplied keys and values. -
of
Returns aBiStream
of three pairs, containing the supplied keys and values. -
of
Returns aBiStream
of 4 pairs, containing the supplied keys and values.- Since:
- 5.6
-
of
Returns aBiStream
of 5 pairs, containing the supplied keys and values.- Since:
- 5.6
-
of
public static <K,V> BiStream<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) Returns aBiStream
of 6 pairs, containing the supplied keys and values.- Since:
- 5.6
-
of
public static <K,V> BiStream<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) Returns aBiStream
of 7 pairs, containing the supplied keys and values.- Since:
- 5.6
-
of
public static <K,V> BiStream<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8) Returns aBiStream
of 8 pairs, containing the supplied keys and values.- Since:
- 5.6
-
of
public static <K,V> BiStream<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9) Returns aBiStream
of 9 pairs, containing the supplied keys and values.- Since:
- 5.6
-
of
public static <K,V> BiStream<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10) Returns aBiStream
of 10 pairs, containing the supplied keys and values.- Since:
- 5.6
-
concat
@SafeVarargs public static <K,V> BiStream<K,V> concat(Map<? extends K, ? extends V> m1, Map<? extends K, ? extends V> m2, Map<? extends K, ? extends V>... rest) Returns aBiStream
of the entries fromm1
,m2
thenrest
in encounter order. For example:Map<AccountId, Account> allAccounts = concat(primaryAccounts, secondaryAccounts).toMap();
- Since:
- 3.0
-
concat
@SafeVarargs public static <K,V> BiStream<K,V> concat(BiStream<? extends K, ? extends V> s1, BiStream<? extends K, ? extends V> s2, BiStream<? extends K, ? extends V>... rest) Returns aBiStream
of the entries froms1
,s2
thenrest
in encounter order. For example:Map<AccountId, Account> allAccounts = concat(primaryAccounts, secondaryAccounts).toMap();
- Since:
- 4.7
-
concat
public static <K,V> BiStream<K,V> concat(Stream<? extends BiStream<? extends K, ? extends V>> biStreams) Returns aBiStream
of pairs frombiStreams
concatenated in encounter order.- Since:
- 3.0
-
zip
Returns aBiStream
in which the first element inleft
is paired with the first element inright
; the second paired with the corresponding second and the third with the corresponding third etc. For example:BiStream.zip(asList(1, 2, 3), asList("one", "two"))
will returnBiStream.of(1, "one", 2, "two")
.The resulting stream will only be as long as the shorter of the two iterables; if one is longer, its extra elements will be ignored.
- Since:
- 3.0
-
zip
Returns aBiStream
in which the first element inleft
is paired with the first element inright
; the second paired with the corresponding second and the third with the corresponding third etc. For example:BiStream.zip(Stream.of(1, 2, 3), Stream.of("one", "two"))
will returnBiStream.of(1, "one", 2, "two")
.The resulting stream will only be as long as the shorter of the two input streams; if one stream is longer, its extra elements will be ignored.
The resulting stream by default runs sequentially regardless of the input streams. This is because the implementation is not efficiently splittable. and may not perform well if run in parallel.
-
biStream
Short-hand forfrom(elements, identity(), identity())
. Typically followed bymapKeys(java.util.function.BiFunction<? super K, ? super V, ? extends K2>)
ormapValues(java.util.function.BiFunction<? super K, ? super V, ? extends V2>)
. For example:static import com.google.common.labs.collect.BiStream.biStream; Map<EmployeeId, Employee> employeesById = biStream(employees) .mapKeys(Employee::id) .toMap();
- Since:
- 3.0
-
biStream
Short-hand forfrom(elements, identity(), identity())
. Typically followed bymapKeys(java.util.function.BiFunction<? super K, ? super V, ? extends K2>)
ormapValues(java.util.function.BiFunction<? super K, ? super V, ? extends V2>)
. For example:static import com.google.common.labs.collect.BiStream.biStream; Map<EmployeeId, Employee> employeesById = biStream(employees) .mapKeys(Employee::id) .toMap();
- Since:
- 3.6
-
biStream
public static <K,V> BiStream<K,V> biStream(Collection<K> keys, Function<? super K, ? extends V> toValue) Returns aBiStream
of mappings betweenkeys
and the corresponding return values of thetoValue
function. For example:BiStream<Request, ListenableFuture<Response>> requestsAndResponses = biStream(requests, service::sendRequest);
- Since:
- 5.6
-
biStream
public static <K,V> BiStream<K,V> biStream(Stream<K> keys, Function<? super K, ? extends V> toValue) Returns aBiStream
of mappings betweenkeys
and the corresponding return values of thetoValue
function. For example:BiStream<Request, ListenableFuture<Response>> requestsAndResponses = biStream(requests, service::sendRequest);
- Since:
- 5.6
-
biStream
public static <K,V> BiStream<K,V> biStream(Function<? super V, ? extends K> toKey, Collection<V> values) Returns aBiStream
of mappings between the key returned by thetoKey
function (when applied to each element ofvalues
), and the element itself.ImmutableListMultimap<UserId, Account> userAccounts = biStream(User::id, users) .flatMapValues(User::accounts) .collect(toImmutableListMultimap());
- Since:
- 5.6
-
biStream
public static <K,V> BiStream<K,V> biStream(Function<? super V, ? extends K> toKey, Stream<V> values) Returns aBiStream
of mappings between the key returned by thetoKey
function (when applied to each element ofvalues
), and the element itself.ImmutableListMultimap<UserId, Account> userAccounts = biStream(User::id, users) .flatMapValues(User::accounts) .collect(toImmutableListMultimap());
- Since:
- 5.6
-
from
Returns aBiStream
of the entries inmap
. -
from
public static <K,V> BiStream<K,V> from(Collection<? extends Map.Entry<? extends K, ? extends V>> entries) Returns aBiStream
of the key value pairs fromentries
. For exampleBiStream.from(multimap.entries())
.- Since:
- 4.7
-
from
@Deprecated public static <T,K, BiStream<K,V> V> from(Collection<T> elements, Function<? super T, ? extends K> toKey, Function<? super T, ? extends V> toValue) Deprecated.UsebiStream(User::id, users)
to createBiStream<UserId, User>
, or, usebiStream(users, User::getAccount)
to createBiStream<User, Account>
. Then usemapKeys(java.util.function.BiFunction<? super K, ? super V, ? extends K2>)
ormapValues(java.util.function.BiFunction<? super K, ? super V, ? extends V2>)
to apply further mappings.Returns aBiStream
ofelements
, each transformed to a pair of values withtoKey
andtoValue
. -
from
@Deprecated public static <T,K, BiStream<K,V> V> from(Stream<T> stream, Function<? super T, ? extends K> toKey, Function<? super T, ? extends V> toValue) Deprecated.UsebiStream(User::id, users)
to createBiStream<UserId, User>
, or, usebiStream(users, User::getAccount)
to createBiStream<User, Account>
. Then usemapKeys(java.util.function.BiFunction<? super K, ? super V, ? extends K2>)
ormapValues(java.util.function.BiFunction<? super K, ? super V, ? extends V2>)
to apply further mappings.Returns aBiStream
of the elements fromstream
, each transformed to a pair of values withtoKey
andtoValue
. -
from
Returns aBiStream
of the pairs fromstream
.- Since:
- 5.1
-
repeat
public static <I,O> BiStream<I,O> repeat(Function<? super I, ? extends O> work, I initial, BiFunction<? super I, ? super O, ? extends Optional<? extends I>> increment) Returns a stream of the inputs and outputs from repeated applications of thework
function. Theinitial
input is passed towork
for the first round, after which theincrement
function is called to determine the input for the next round. This process repeats until theincrement
function returnsOptional.empty()
.A common use case is pagination. For example, if you have a list API with pagination support, the following code retrieves all pages eagerly:
You can turn the above code to a lazy stream so that callers can short-circuit when they need to without having to exhaust all pages:ImmutableList<Foo> listAllFoos() { ImmutableList.Builder<Foo> builder = ImmutableList.builder(); ListFooRequest.Builder request = ListFooRequest.newBuilder()...; do { ListFooResponse response = service.listFoos(request.build()); builder.addAll(response.getFoos()); request.setPageToken(response.getNextPageToken()); } while (!request.getPageToken().isEmpty()); return builder.build(); }
Stream<Foo> listAllFoos() { return BiStream.repeat( service::listFoos, initialRequest, (request, response) -> optional( response.hasNextPageToken(), request.toBuilder().setPageToken(response.getNextPageToken()).build())) .flatMapToObj((request, response) -> response.getAllFoos().stream()); }
- Type Parameters:
I
- the input typeO
- the output type- Parameters:
work
- the function to repeat. Null outputs are passed through as is.initial
- the initial input to pass to thework
function. Cannot be null.increment
- the function to get the next input given the current input and output.- Returns:
- A BiStream of the inputs and outputs of the
work
function. The stream is lazy in thatwork
won't be called until the stream is being consumed; and it won't be called again until the second pair of input and output are being consumed, etc. - Since:
- 5.5
-
fromEntries
public static <K,V, BiStream<K,E extends Map.Entry<? extends K, ? extends V>> V> fromEntries(Stream<E> entryStream) - Since:
- 7.1
-
mapToObj
Returns aStream
consisting of the results of applyingmapper
to each pair in thisBiStream
. -
mapToObjIfPresent
public final <T> Stream<T> mapToObjIfPresent(BiFunction<? super K, ? super V, ? extends Optional<? extends T>> mapper) Returns aStream
consisting of the results of applyingmapper
to each pair in thisBiStream
. Ifmapper
function returns empty, the pair is discarded.- Since:
- 4.7
-
map
public <K2,V2> BiStream<K2,V2> map(BiFunction<? super K, ? super V, ? extends K2> keyMapper, BiFunction<? super K, ? super V, ? extends V2> valueMapper) Returns aBiStream
consisting of the results of applyingkeyMapper
andvalueMapper
to the pairs in thisBiStream
. -
map
public final <K2,V2> BiStream<K2,V2> map(BiFunction<? super K, ? super V, ? extends Both<? extends K2, ? extends V2>> mapper) Returns aBiStream
consisting of the result pairs of applyingmapper
to the pairs in thisBiStream
.For example, the following code parses each line read from a file in the format of "key: value", and upon expected format, reports the line number:
import static com.google.mu.util.Substring.first; BiStream.zip(MoreStreams.indexesFrom(1), readLines().stream()) .map((lineNumber, line) -> first(':') .splitThenTrim(line) .orElseThrow(() -> new IllegalArgumentException("line: " + lineNumber))) ...;
- Since:
- 5.2
-
mapIfPresent
public final <K2,V2> BiStream<K2,V2> mapIfPresent(BiFunction<? super K, ? super V, ? extends BiOptional<? extends K2, ? extends V2>> mapper) Returns aBiStream
consisting of the results of applyingmapper
function to the pairs in thisBiStream
. Ifmapper
returns empty, the pair is discarded.- Since:
- 5.0
-
mapToDouble
-
mapToInt
-
mapToLong
-
mapKeys
Returns aBiStream
of pairs whose keys are the result of applyingkeyMapper
to the key of each pair in thisBiStream
, and whose values are unchanged. -
mapKeys
Maps each key to another key of typeK2
. -
mapValues
Maps each value to another value of typeV2
. -
mapValues
Maps each value to another value of typeV2
. -
flatMapToObj
public final <T> Stream<T> flatMapToObj(BiFunction<? super K, ? super V, ? extends Stream<? extends T>> mapper) Maps a single pair to zero or more objects of typeT
.If a mapped stream is null, an empty stream is used instead.
-
flatMapToDouble
public final DoubleStream flatMapToDouble(BiFunction<? super K, ? super V, ? extends DoubleStream> mapper) Maps a single pair to zero or moredouble
s.If a mapped stream is null, an empty stream is used instead.
-
flatMapToInt
Maps a single pair to zero or moreint
s.If a mapped stream is null, an empty stream is used instead.
-
flatMapToLong
Maps a single pair to zero or morelong
s.If a mapped stream is null, an empty stream is used instead.
-
flatMap
public final <K2,V2> BiStream<K2,V2> flatMap(BiFunction<? super K, ? super V, ? extends BiStream<? extends K2, ? extends V2>> mapper) Maps each pair in this stream to zero or more pairs in anotherBiStream
. For example the following code snippet repeats each pair in aBiStream
for 3 times:BiStream<K, V> repeated = stream.flatMap((k, v) -> BiStream.of(k, v, k, v, k, v));
If a mapped stream is null, an empty stream is used instead.
-
flatMapKeys
public final <K2> BiStream<K2,V> flatMapKeys(BiFunction<? super K, ? super V, ? extends Stream<? extends K2>> keyMapper) Maps each key to zero or more keys of typeK2
.If a mapped stream is null, an empty stream is used instead.
-
flatMapKeys
public final <K2> BiStream<K2,V> flatMapKeys(Function<? super K, ? extends Stream<? extends K2>> keyMapper) Maps each key to zero or more keys of typeK2
.If a mapped stream is null, an empty stream is used instead.
-
mapKeysIfPresent
GivenkeyMapping
that maps the keys of typeK
to elements of typeK2
, returns aBiStream
of type<K2, V>
.Keys not found in
keyMap
(or mapped to null) are discarded.For example, if you need to turn a
BiStream<StudentId, Score>
toBiStream<Student, Score>
by looking up the student id in aMap<StudentId, Student>
, you can do:Map<StudentId, Score> scores = ...; BiStream.from(scores) .mapKeysIfPresent(studentsMap) ...;
The above code is equivalent to the following variants:
or:Map<StudentId, Score> scores = ...; BiStream.from(scores) .mapKeys(studentsMap::get) .mapKeys(Optional::ofNullable) .flatMapKeys(Streams::stream) ...;
Map<StudentId, Score> scores = ...; BiStream.from(scores) .mapKeys(studentsMap::get) .filterKeys(Objects::nonNull) ...;
- Since:
- 4.7
-
mapKeysIfPresent
public final <K2> BiStream<K2,V> mapKeysIfPresent(Function<? super K, ? extends Optional<? extends K2>> keyMapper) Returns aBiStream
of pairs whose keys are the result of applyingkeyMapper
to the key of each pair in thisBiStream
, and whose values are unchanged. IfkeyMapper
function returns empty, the pair is discarded.For example the following code counts the total number of unique patients per hospital, from doctors' affiliated hospitals:
Map<Doctor, Patient> doctorAndPatients = ...; Map<Hospital, Long> hospitalPatientCounts = BiStream.from(doctorAndPatients) .mapKeysIfPresent(Doctor::optionalAffliatedHospital) .collect(toImmutableMap(counting()));
- Since:
- 4.7
-
mapKeysIfPresent
public final <K2> BiStream<K2,V> mapKeysIfPresent(BiFunction<? super K, ? super V, ? extends Optional<? extends K2>> keyMapper) Returns aBiStream
of pairs whose keys are the result of applyingkeyMapper
to each pair in thisBiStream
, and whose values are unchanged. IfkeyMapper
function returns empty, the pair is discarded.- Since:
- 4.7
-
flatMapValues
public final <V2> BiStream<K,V2> flatMapValues(BiFunction<? super K, ? super V, ? extends Stream<? extends V2>> valueMapper) Maps each value to zero or more values of typeV2
.If a mapped stream is null, an empty stream is used instead.
-
flatMapValues
public final <V2> BiStream<K,V2> flatMapValues(Function<? super V, ? extends Stream<? extends V2>> valueMapper) Maps each value to zero or more values of typeV2
.If a mapped stream is null, an empty stream is used instead.
-
mapValuesIfPresent
GivenvalueMapping
that maps values of typeV
to result values of typeV2
, returns aBiStream
of type<K, V2>
.Values not found in
valueMap
(or mapped to null) are discarded.For example, if you need to turn a
Multimap<ClassId, StudentId>
toMultimap<ClassId, Student>
by looking up the student id in aMap<StudentId, Student>
, you can do:Multimap<ClassId, StudentId> registration = ...; ImmutableSetMultimap<ClassId, Student> roster = BiStream.from(registration) .mapValuesIfPresent(studentsMap) .collect(toImmutableSetMultimap());
The above code is equivalent to the following variants:
or:Multimap<ClassId, StudentId> registration = ...; ImmutableSetMultimap<ClassId, Student> roster = BiStream.from(registration) .mapValues(studentsMap::get) .mapValues(Optional::ofNullable) .flatMapValues(Streams::stream) .collect(toImmutableSetMultimap());
Multimap<ClassId, StudentId> registration = ...; ImmutableSetMultimap<ClassId, Student> roster = BiStream.from(registration) .mapValues(studentsMap::get) .filterValues(Objects::nonNull) .collect(toImmutableSetMultimap());
- Since:
- 4.7
-
mapValuesIfPresent
public final <V2> BiStream<K,V2> mapValuesIfPresent(Function<? super V, ? extends Optional<? extends V2>> valueMapper) Returns aBiStream
of pairs whose values are the result of applyingvalueMapper
to the value of each pair in thisBiStream
, and whose keys are unchanged. IfvalueMapper
function returns empty, the pair is discarded.For example the following code collects all unique insurance companies per doctor:
Map<Doctor, Patient> doctorAndPatients = ...; ImmutableSetMultimap<Doctor, InsuranceCompany> insurancesPerDoctor = BiStream.from(doctorAndPatients) .mapValuesIfPresent(Partient::optionalInsurarnce) .collect(toImmutableSetMultimap());
- Since:
- 4.7
-
mapValuesIfPresent
public final <V2> BiStream<K,V2> mapValuesIfPresent(BiFunction<? super K, ? super V, ? extends Optional<? extends V2>> valueMapper) Returns aBiStream
of pairs whose values are the result of applyingvalueMapper
to each pair in thisBiStream
, and whose keys are unchanged. IfvalueMapper
function returns empty, the pair is discarded.- Since:
- 4.7
-
peek
Returns aBiStream
consisting of the pairs of this stream, additionally invokingaction
on each pair as pairs are consumed from the resulting stream. -
filter
Filter this stream to only pairs matchingpredicate
.Note that if you are passing in a lambda with the
!
operator, consider usingskipIf(java.util.function.BiPredicate<? super K, ? super V>)
instead that might even allow you to use method reference. -
filterKeys
Filter this stream to only pairs whose key matchespredicate
.Note that if you are passing in a lambda with the
!
operator, consider usingskipKeysIf(java.util.function.Predicate<? super K>)
instead that might even allow you to use method reference. -
filterValues
Filter this stream to only pairs whose value matchespredicate
.Note that if you are passing in a lambda with the
!
operator, consider usingskipValuesIf(java.util.function.Predicate<? super V>)
instead that might even allow you to use method reference. -
skipIf
Filter this stream to exclude pairs matchingpredicate
.Useful especially when it allows you to use method reference. For example:
tasks.stream() .collect(crossJoining(Arrays.stream(MachineType.values())) .skipIf(Worker::blacklistsMachine) ...
- Since:
- 5.1
-
skipKeysIf
Filter this stream to exclude pairs whose key matchespredicate
.Useful especially when it allows you to use method reference. For example:
BiStream.from(rosters) .skipKeysIf(inactiveUserIds::contains) ...
- Since:
- 5.1
-
skipValuesIf
Filter this stream to exclude pairs whose value matchespredicate
.Useful especially when it allows you to use method reference. For example:
BiStream.zip(userIds, userNames) .skipValuesIf(String::isEmpty) ...
- Since:
- 5.1
-
append
Returns aBiStream
consisting of the pairs in this stream, followed by the pairs inother
.NOTE: This method is implemented using
Stream.concat(java.util.stream.Stream<? extends T>, java.util.stream.Stream<? extends T>)
; therefore, the same warnings about deeply-nested combined streams also apply to this method. In particular, avoid calling this method in a loop to combine many streams together. -
append
Returns aBiStream
consisting of the pairs in this stream, followed by the pair ofkey
andvalue
.NOTE: This method is implemented using
Stream.concat(java.util.stream.Stream<? extends T>, java.util.stream.Stream<? extends T>)
; therefore, the same warnings about deeply-nested combined streams also apply to this method. In particular, avoid calling this method in a loop to combine many streams together. -
keys
Returns aStream
consisting of only the keys from each pair in this stream. -
values
Returns aStream
consisting of only the values from each pair in this stream. -
inverse
Returns aBiStream
where each pair is a pair from this stream with the key and value swapped. -
forEach
Performsaction
for each pair in this stream. -
forEachOrdered
Performsaction
for each pair in this stream, in order. -
allMatch
Returns true if all pairs in this stream matchpredicate
. -
anyMatch
Returns true if any pair in this stream matchespredicate
. -
noneMatch
Returns true if no pairs in this stream matchpredicate
. -
findFirst
Returns the first pair from this stream, orBiOptional.empty()
if the stream is empty.- Throws:
NullPointerException
- if the chosen pair includes null- Since:
- 5.0
-
findAny
Returns any pair from this stream, orBiOptional.empty()
if the stream is empty.- Throws:
NullPointerException
- if the chosen pair includes null- Since:
- 5.0
-
limit
Returns aBiStream
consisting of the only the firstmaxSize
pairs of this stream. -
skip
Returns aBiStream
consisting of the remaining pairs from this stream, after discarding the firstn
pairs. -
distinct
Returns aBiStream
consisting of only the distinct pairs (according toObject.equals(Object)
for both key and value). -
sortedByKeys
Returns aBiStream
consisting of the pairs in this stream, in the order produced by applyingcomparator
on the keys of each pair. -
sortedByValues
Returns aBiStream
consisting of the pairs in this stream, in the order produced by applyingcomparator
on the values of each pair. -
sortedBy
public final <T> BiStream<K,V> sortedBy(BiFunction<? super K, ? super V, T> sortKeyFunction, Comparator<? super T> comparator) Returns aBiStream
consisting of the pairs in this stream, in the order produced by applyingcomparator
on the result of applying thesortKeyFunction
.- Since:
- 6.6
-
sorted
Returns aBiStream
consisting of the pairs in this stream, in the order produced by applying thebyKey
comparator on the keys of each pair, and then thebyValue
comparator on the values of pairs with equal keys.To sort by value then by key, consider using
inverse()
first. -
count
public final long count()Returns the count of pairs in this stream. -
toMap
Returns an immutableMap
that is the result of collecting the pairs in this stream. If a duplicate key is encountered, throws anIllegalStateException
.While this is a convenient shortcut of
collect(Collectors::toMap)
, if you have aBiStream<SubFoo, SubBar>
, the return type oftoMap()
will beMap<SubFoo, SubBar>
. To collect toMap<Foo, Bar>
, use the equivalentcollect(Collectors::toMap)
orcollect(BiCollectors.toMap())
. -
collect
Returns an object of typeR
that is the result of collecting the pairs in this stream usingcollector
.Please note that any
Collector
-returning factory method can be directly "method referenced" asBiCollector
if it accepts twoFunction
parameters corresponding to the "key" and the "value" parts respectively. For example:collect(Collectors::toConcurrentMap)
,collect(ImmutableSetMultimap::toImmutableSetMultimap)
,collect(Maps::toImmutableEnumMap)
,collect(ImmutableBiMap::toImmutableBiMap)
.In addition, check out
BiCollectors
for some other usefulBiCollector
implementations. -
collect
public final <T,R> R collect(BiCollector<? super K, ? super V, T> collector, Function<? super T, R> finisher) Equivalent tocollect(collectingAndThen(collector, finisher))
but helps to save syntactic noise.This is mainly used for "return" statements where you have a long BiStream chain, only the last* step needs to pass the return value of
collect()
to a final method call, for example:
This syntax breaks the first-thing-first order of the BiStream pipeline by showing the last step at the top-most line. Alternatively, one can declare a local variable to hold the return value ofreturn new Ledger( BiStream.from(...) .mapKeys(...) .flatMapValues(...) ... .collect(toImmutableMap()));
collect()
. But sometimes it's undesirable if the intermediary object's type is implementation-detail-ish or just too verbose.Using this method, the above example can be changed to pipeline-friendly syntax with less indentation:
return BiStream.from(...) .mapKeys(...) .flatMapValues(...) ... .collect(toImmutableMap(), Ledger::new);
- Since:
- 5.6
-
collect
public abstract <A> A collect(A container, BiAccumulator<? super A, ? super K, ? super V> accumulator) Performs mutable reduction, as incollect(ImmutableMap.builder(), ImmutableMap.Builder::put)
.More realistically (since you'd likely use
collect(toImmutableMap())
instead for ImmutableMap), you could collect pairs into two repeated proto fields:BiStream.zip(shardRequests, shardResponses) .filter(...) .collect( BatchResponse.newBuilder(), (builder, req, resp) -> builder.addShardRequest(req).addShardResponse(resp)) .build();
While
collect(BiCollector)
may perform parallel reduction if the underlying stream is parallel, this reduction is guaranteed to be sequential and single-threaded.Returns the populated
container
instance.- Since:
- 5.0
-
close
public abstract void close()Closes any resources associated with this stream, typically used in a try-with-resources statement.- Specified by:
close
in interfaceAutoCloseable
-
groupConsecutiveBy
public final <G,A, BiStream<G,R> R> groupConsecutiveBy(Function<? super K, ? extends G> classifier, Collector<? super V, A, ? extends R> groupCollector) Returns aBiStream
consisting of consecutive groupings from this stream. Consecutive pairs whose key maps to the same group according toclassifier
will have their values grouped together usinggroupCollector
.For example to lazily summarize a large, pre-sorted stock price data stream per day:
biStream(stockPriceData) .groupConsecutiveBy(PriceDatum::day, summarizingDouble(PriceDatum::price)) .toMap();
Unlike JDK
groupingBy()
collectors, the returned BiStream consumes the input elements lazily and only requiresO(groupCollector)
space for the current consecutive elements group. For instance thegroupConsecutiveBy(Event::type, counting())
stream takes O(1) space. While this makes it more efficient to process large streams, the input data often need to be pre-sorted for the grouping to be useful.To apply grouping beyond consecutive elements, use
collect(BiCollectors.groupingBy(classifier, groupCollector))
instead.Consecutive keys mapped to null by
classifier
will be grouped together.- Parameters:
classifier
- The function to determine the group key. Because it's guaranteed to be invoked once and only once per entry, and that the returned BiStream is sequential and respects encounter order, this function is allowed to have side effects.- Since:
- 5.4
-
groupConsecutiveBy
public final <G> BiStream<G,V> groupConsecutiveBy(Function<? super K, ? extends G> classifier, BinaryOperator<V> groupReducer) Returns a lazyBiStream
of the consecutive groups of pairs from this stream. Consecutive pairs whose key maps to the same group according toclassifier
will have their values reduced using thegroupReducer
function.For example to lazily find the daily opening stock price from a large, pre-sorted stock data stream:
biStream(stockPriceDataSortedByTime) .groupConsecutiveBy(PriceDatum::day, (a, b) -> a) ,toMap();
Unlike JDK
groupingBy()
collectors, the returned BiStream consumes the input elements lazily and only requiresO(1)
space. While this makes it more efficient to process large streams, the input data often need to be pre-sorted for the grouping to be useful.To apply grouping beyond consecutive elements, use
collect(BiCollectors.groupingBy(classifier, groupReducer))
instead.Consecutive null keys are grouped together.
- Parameters:
classifier
- The function to determine the group key. Because it's guaranteed to be invoked once and only once per entry, and that the returned BiStream is sequential and respects encounter order, this function is allowed to have side effects.- Since:
- 5.4
-
groupConsecutiveBy
public final <G,A, BiStream<G,R> R> groupConsecutiveBy(BiFunction<? super K, ? super V, ? extends G> classifier, BiCollector<? super K, ? super V, R> groupCollector) Returns aBiStream
consisting of consecutive groupings from this stream. Consecutive pairs mapping to the same group according toclassifier
will be grouped together usinggroupCollector
.This can be useful when you need to apply nested groupings, for example, to first group consecutive events by year, then by continuity (happened within 24 hours):
import static com.google.mu.util.stream.BiiCollectors.collectingAndThen; ImmutableListMultimap<Integer, List<Event>> continuousEventsByYear = biStream(events) .mapKeys(Event::date) .groupConsecutiveBy( (date, event) -> date.year(), collectingAndThen( annual -> annual.groupConsecutiveIf( (d1, d2) -> Duration.between(d1, d2).compareTo(Duration.ofHours(24)) < 0, toList()))) .collect(flatteningToImmutableListMultimap(subgroups -> subgroups));
Unlike JDK
groupingBy()
collectors, the returned BiStream consumes the input elements lazily and only requiresO(groupCollector)
space for the current consecutive elements group. For instance thegroupConsecutiveBy(Event::type, counting())
stream takes O(1) space. While this makes it more efficient to process large streams, the input data often need to be pre-sorted for the grouping to be useful.To apply grouping beyond consecutive elements, use
collect(BiCollectors.groupingBy(classifier, groupCollector))
instead.Consecutive pairs mapped to null by
classifier
will be grouped together.- Parameters:
classifier
- The function to determine the group key. Because it's guaranteed to be invoked once and only once per entry, and that the returned BiStream is sequential and respects encounter order, this function is allowed to have side effects.- Since:
- 5.5
-
groupConsecutiveIf
public final <R> Stream<R> groupConsecutiveIf(BiStream.Partitioner<? super K, ? super V> sameGroup, BiCollector<? super K, ? super V, R> groupCollector) Returns a lazyStream
of the consecutive groups of values from this stream. Two consecutive entries belong to the same group ifsameGroup.belong(key1, value1, key2, value2)
is true. Pairs belonging to the same group are grouped together usinggroupCollector
.The
sameGroup
predicate is always evaluated with two consecutive pairs in encounter order.The following example identifies price changes above a gap threshold from a stock's historical price:
Map<DateTime, Double> historicalPrices = ...; ImmutableList<ImmutableMap<DateTime, Double>> priceClusters = biStream(historicalPrices) .groupConsecutiveIf((d1, p1, d2, p2) -> abs(p1 - p2) < gap, toImmutableMap()) .collect(toImmutableList());
Unlike JDK
groupingBy()
collectors, the returned Stream consumes the input elements lazily and only requiresO(groupCollector)
space for the current consecutive elements group. While this makes it more efficient to process large streams, the input data often need to be pre-sorted for the grouping to be useful.Null elements are allowed as long as the
sameGroup
predicate andgroupCollector
allow nulls.- Since:
- 5.6
-
groupConsecutiveIf
public final <A,R> Stream<R> groupConsecutiveIf(BiPredicate<? super K, ? super K> sameGroup, Collector<? super V, A, R> groupCollector) Returns a lazyStream
of the consecutive groups of values from this stream. Two consecutive entries belong to the same group ifsameGroup.test(key1, key2)
is true. Values belonging to the same group are grouped together usinggroupCollector
.The
sameGroup
predicate is always evaluated with two consecutive keys in encounter order.The following example identifies price changes above a gap threshold from a stock's historical price:
Stream<DoubleSummaryStatistics> priceClusters = biStream(stockPriceData) .groupConsecutiveIf((a, b) -> abs(a - b) < gap, summarizingDouble());
Unlike JDK
groupingBy()
collectors, the returned Stream consumes the input elements lazily and only requiresO(groupCollector)
space for the current consecutive elements group. While this makes it more efficient to process large streams, the input data often need to be pre-sorted for the grouping to be useful.Null elements are allowed as long as the
sameGroup
predicate andgroupCollector
allow nulls.- Since:
- 5.4
-
groupConsecutiveIf
public final Stream<V> groupConsecutiveIf(BiPredicate<? super K, ? super K> sameGroup, BinaryOperator<V> groupReducer) Returns a lazyStream
of the consecutive groups of values from this stream. Two consecutive entries belong to the same group ifsameGroup.test(key1, key2)
is true. Values belonging to the same group are reduced usinggroupReducer
.The
sameGroup
predicate is always evaluated with two consecutive keys in encounter order.Unlike JDK
groupingBy()
collectors, the returned Stream consumes the input elements lazily and only requiresO(groupCollector)
space for the current consecutive elements group. While this makes it more efficient to process large streams, the input data often need to be pre-sorted for the grouping to be useful.Null elements are allowed as long as the
sameGroup
predicate andgroupCollector
allow nulls.- Since:
- 5.4
-
biStream(User::id, users)
to createBiStream<UserId, User>
, or, usebiStream(users, User::getAccount)
to createBiStream<User, Account>
.