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
Nested ClassesModifier and TypeClassDescriptionstatic final classBuilder forBiStream.static interfaceA predicate used to partition aBiStreaminto sub-groups of consecutive pairs. -
Method Summary
Modifier and TypeMethodDescriptionabstract booleanallMatch(BiPredicate<? super K, ? super V> predicate) Returns true if all pairs in this stream matchpredicate.abstract booleananyMatch(BiPredicate<? super K, ? super V> predicate) Returns true if any pair in this stream matchespredicate.Returns aBiStreamconsisting of the pairs in this stream, followed by the pairs inother.Returns aBiStreamconsisting of the pairs in this stream, followed by the pairs inmap.Returns aBiStreamconsisting of the pairs in this stream, followed by the pair ofkeyandvalue.static <K,V> BiStream <K, V> biStream(Collection<K> keys, Function<? super K, ? extends V> toValue) Returns aBiStreamof mappings betweenkeysand the corresponding return values of thetoValuefunction.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 aBiStreamof mappings between the key returned by thetoKeyfunction (when applied to each element ofvalues), and the element itself.static <K,V> BiStream <K, V> Returns aBiStreamof mappings between the key returned by thetoKeyfunction (when applied to each element ofvalues), and the element itself.static <K,V> BiStream <K, V> Returns aBiStreamof mappings betweenkeysand the corresponding return values of thetoValuefunction.static <T> BiStream<T, T> Short-hand forfrom(elements, identity(), identity()).static <K,V> BiStream.Builder <K, V> builder()Returns a newBiStream.Builder.abstract voidclose()Closes any resources associated with this stream, typically used in a try-with-resources statement.abstract <A> Acollect(A container, BiAccumulator<? super A, ? super K, ? super V> accumulator) Performs mutable reduction, as incollect(ImmutableMap.builder(), ImmutableMap.Builder::put).abstract <R> Rcollect(BiCollector<? super K, ? super V, R> collector) Returns an object of typeRthat 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 aBiStreamof the entries froms1,s2thenrestin 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 aBiStreamof the entries fromm1,m2thenrestin encounter order.static <K,V> BiStream <K, V> Returns aBiStreamof pairs frombiStreamsconcatenated in encounter order.concatenating(Function<? super T, ? extends BiStream<? extends K, ? extends V>> toBiStream) Returns aCollectorthat concatenatesBiStreamobjects derived from the input elements using the giventoBiStreamfunction.final longcount()Returns the count of pairs in this stream.crossJoining(Stream<R> right) Returns aCollectorthat will pair each input element with each element fromrightinto a newBiStream.distinct()Returns aBiStreamconsisting 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 DoubleStreamflatMapToDouble(BiFunction<? super K, ? super V, ? extends DoubleStream> mapper) Maps a single pair to zero or moredoubles.final IntStreamflatMapToInt(BiFunction<? super K, ? super V, ? extends IntStream> mapper) Maps a single pair to zero or moreints.final LongStreamflatMapToLong(BiFunction<? super K, ? super V, ? extends LongStream> mapper) Maps a single pair to zero or morelongs.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 voidforEach(BiConsumer<? super K, ? super V> action) Performsactionfor each pair in this stream.abstract voidforEachOrdered(BiConsumer<? super K, ? super V> consumer) Performsactionfor each pair in this stream, in order.static <K,V> BiStream <K, V> from(Collection<? extends Map.Entry<? extends K, ? extends V>> entries) Returns aBiStreamof 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 aBiStreamof the entries inmap.static <K,V> BiStream <K, V> Returns aBiStreamof 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 aBiStreamconsisting of consecutive groupings from this stream.groupConsecutiveBy(Function<? super K, ? extends G> classifier, BinaryOperator<V> groupReducer) Returns a lazyBiStreamof 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 aBiStreamconsisting 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 lazyStreamof the consecutive groups of values from this stream.groupConsecutiveIf(BiPredicate<? super K, ? super K> sameGroup, BinaryOperator<V> groupReducer) Returns a lazyStreamof 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 lazyStreamof the consecutive groups of values from this stream.groupingBy(Function<? super T, ? extends K> classifier) Returns aCollectorthat groups the input elements byclassifierand 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 aCollectorthat groups the input elements byclassifierand reduces the values mapping to the same key usingmapperthenreducer.groupingBy(Function<? super T, ? extends K> classifier, Collector<? super T, ?, V> valueCollector) Returns aCollectorthat groups the input elements byclassifierand collects the values mapping to the same key usingvalueCollector.groupingBy(Function<? super V, ? extends K> classifier, BinaryOperator<V> reducer) Returns aCollectorthat groups the input elements byclassifierand 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 aCollectorgrouping 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 aCollectorgrouping 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 aCollectorgrouping input elements by each of the multiple keys returned by thekeysFunction.inverse()Returns aBiStreamwhere each pair is a pair from this stream with the key and value swapped.keys()Returns aStreamconsisting of only the keys from each pair in this stream.limit(int maxSize) Returns aBiStreamconsisting of the only the firstmaxSizepairs of this stream.final <K2,V2> BiStream <K2, V2> map(BiFunction<? super K, ? super V, ? extends Both<? extends K2, ? extends V2>> mapper) Returns aBiStreamconsisting of the result pairs of applyingmapperto 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 aBiStreamconsisting of the results of applyingkeyMapperandvalueMapperto the pairs in thisBiStream.final <K2,V2> BiStream <K2, V2> mapIfPresent(BiFunction<? super K, ? super V, ? extends BiOptional<? extends K2, ? extends V2>> mapper) Returns aBiStreamconsisting of the results of applyingmapperfunction to the pairs in thisBiStream.mapKeys(BiFunction<? super K, ? super V, ? extends K2> keyMapper) Returns aBiStreamof pairs whose keys are the result of applyingkeyMapperto 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 aBiStreamof pairs whose keys are the result of applyingkeyMapperto each pair in thisBiStream, and whose values are unchanged.mapKeysIfPresent(Function<? super K, ? extends Optional<? extends K2>> keyMapper) Returns aBiStreamof pairs whose keys are the result of applyingkeyMapperto the key of each pair in thisBiStream, and whose values are unchanged.mapKeysIfPresent(Map<? super K, ? extends K2> keyMapping) GivenkeyMappingthat maps the keys of typeKto elements of typeK2, returns aBiStreamof type<K2, V>.abstract DoubleStreammapToDouble(ToDoubleBiFunction<? super K, ? super V> mapper) abstract IntStreammapToInt(ToIntBiFunction<? super K, ? super V> mapper) abstract LongStreammapToLong(ToLongBiFunction<? super K, ? super V> mapper) abstract <T> Stream<T> mapToObj(BiFunction<? super K, ? super V, ? extends T> mapper) Returns aStreamconsisting of the results of applyingmapperto each pair in thisBiStream.final <T> Stream<T> mapToObjIfPresent(BiFunction<? super K, ? super V, ? extends Optional<? extends T>> mapper) Returns aStreamconsisting of the results of applyingmapperto 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 aBiStreamof pairs whose values are the result of applyingvalueMapperto each pair in thisBiStream, and whose keys are unchanged.mapValuesIfPresent(Function<? super V, ? extends Optional<? extends V2>> valueMapper) Returns aBiStreamof pairs whose values are the result of applyingvalueMapperto the value of each pair in thisBiStream, and whose keys are unchanged.mapValuesIfPresent(Map<? super V, ? extends V2> valueMapping) GivenvalueMappingthat maps values of typeVto result values of typeV2, returns aBiStreamof type<K, V2>.final booleannoneMatch(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 aBiStreamof a single pair containingkeyandvalue.static <K,V> BiStream <K, V> of(K k1, V v1, K k2, V v2) Returns aBiStreamof 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 aBiStreamof 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 aBiStreamof 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 aBiStreamof 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 aBiStreamof 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 aBiStreamof 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 aBiStreamof 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 aBiStreamof 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 aBiStreamof 10 pairs, containing the supplied keys and values.peek(BiConsumer<? super K, ? super V> action) Returns aBiStreamconsisting of the pairs of this stream, additionally invokingactionon 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 theworkfunction.skip(int n) Returns aBiStreamconsisting of the remaining pairs from this stream, after discarding the firstnpairs.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 aBiStreamconsisting of the pairs in this stream, in the order produced by applying thebyKeycomparator on the keys of each pair, and then thebyValuecomparator on the values of pairs with equal keys.sortedBy(BiFunction<? super K, ? super V, T> sortKeyFunction, Comparator<? super T> comparator) Returns aBiStreamconsisting of the pairs in this stream, in the order produced by applyingcomparatoron the result of applying thesortKeyFunction.sortedByKeys(Comparator<? super K> comparator) Returns aBiStreamconsisting of the pairs in this stream, in the order produced by applyingcomparatoron the keys of each pair.sortedByValues(Comparator<? super V> comparator) Returns aBiStreamconsisting of the pairs in this stream, in the order produced by applyingcomparatoron the values of each pair.Returns aCollectorthat accumulates every neighboring pair of elements into a newBiStream.Returns aCollectorthat copies each input element as a pair of itself into an equivalentBiStream.toBiStream(Function<? super E, ? extends Both<? extends K, ? extends V>> toPair) Returns aCollectorthat 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 aCollectorthat splits each input element as a pair and collects them into aBiStream.toMap()Returns an immutableMapthat is the result of collecting the pairs in this stream.values()Returns aStreamconsisting of only the values from each pair in this stream.static <L,R> BiStream <L, R> zip(Collection<L> left, Collection<R> right) Returns aBiStreamin which the first element inleftis 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 aBiStreamin which the first element inleftis paired with the first element inright; the second paired with the corresponding second and the third with the corresponding third etc.
-
Method Details
-
builder
-
groupingBy
public static <K,V> Collector<V, ?, BiStream<K,V>> groupingBy(Function<? super V, ? extends K> classifier, BinaryOperator<V> reducer) Returns aCollectorthat groups the input elements byclassifierand 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, ?, BiStream<K,V> V>> groupingBy(Function<? super T, ? extends K> classifier, Function<? super T, ? extends V> mapper, BinaryOperator<V> reducer) Returns aCollectorthat groups the input elements byclassifierand reduces the values mapping to the same key usingmapperthenreducer.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, ?, BiStream<K,List<T>>> groupingBy(Function<? super T, ? extends K> classifier) Returns aCollectorthat groups the input elements byclassifierand 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, ?, BiStream<K,V> V>> groupingBy(Function<? super T, ? extends K> classifier, Collector<? super T, ?, V> valueCollector) Returns aCollectorthat groups the input elements byclassifierand 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)ifBiMapis needed.Entries are collected in encounter order.
- Since:
- 3.0
-
groupingByEach
public static <T,K, Collector<T, ?, BiStream<K,V> V>> groupingByEach(Function<? super T, ? extends Stream<? extends K>> keysFunction, Collector<T, ?, V> groupCollector) Returns aCollectorgrouping 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, ?, BiStream<K,V, G> G>> groupingByEach(Function<? super T, ? extends Stream<? extends K>> keysFunction, Function<? super T, ? extends V> valueFunction, Collector<V, ?, G> groupCollector) Returns aCollectorgrouping input elements by each of the multiple keys returned by thekeysFunction. The input element is passed to thevalueFunctionand 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, ?, BiStream<K,V> V>> groupingByEach(Function<? super T, ? extends Stream<? extends K>> keysFunction, Function<? super T, ? extends V> valueFunction, BinaryOperator<V> groupReducer) Returns aCollectorgrouping 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, ?, BiStream<K,V> V>> concatenating(Function<? super T, ? extends BiStream<? extends K, ? extends V>> toBiStream) Returns aCollectorthat concatenatesBiStreamobjects derived from the input elements using the giventoBiStreamfunction.For example:
Map<EmployeeId, Task> billableTaskAssignments = projects.stream() .collect(concatenating(p -> BiStream.from(p.getTaskAssignments()))) .filterValues(Task::billable) .toMap();- Since:
- 3.0
-
crossJoining
Returns aCollectorthat will pair each input element with each element fromrightinto 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
BiStreamtakesO(n)space wherenis the size of the input elements. The "cross-joining" with therightstream is computed on-the-fly withO(1)memory cost.- Since:
- 3.0
-
toAdjacentPairs
Returns aCollectorthat 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 outputBiStreamis one less than the length of the input.- Since:
- 3.2
-
toBiStream
public static <E,K, Collector<E, ?, BiStream<K,V> V>> toBiStream(Function<? super E, ? extends K> toKey, Function<? super E, ? extends V> toValue) Returns aCollectorthat 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, ?, BiStream<K,V> V>> toBiStream(Function<? super E, ? extends Both<? extends K, ? extends V>> toPair) Returns aCollectorthat 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 aCollectorthat 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 aBiStreamof a single pair containingkeyandvalue. -
of
Returns aBiStreamof two pairs, containing the supplied keys and values. -
of
Returns aBiStreamof three pairs, containing the supplied keys and values. -
of
Returns aBiStreamof 4 pairs, containing the supplied keys and values.- Since:
- 5.6
-
of
Returns aBiStreamof 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 aBiStreamof 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 aBiStreamof 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 aBiStreamof 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 aBiStreamof 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 aBiStreamof 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 aBiStreamof the entries fromm1,m2thenrestin 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 aBiStreamof the entries froms1,s2thenrestin encounter order. For example:Map<AccountId, Account> allAccounts = concat(primaryAccounts, secondaryAccounts).toMap();- Since:
- 4.7
-
concat
-
zip
Returns aBiStreamin which the first element inleftis 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 aBiStreamin which the first element inleftis 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 aBiStreamof mappings betweenkeysand the corresponding return values of thetoValuefunction. 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 aBiStreamof mappings betweenkeysand the corresponding return values of thetoValuefunction. 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 aBiStreamof mappings between the key returned by thetoKeyfunction (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 aBiStreamof mappings between the key returned by thetoKeyfunction (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
-
from
public static <K,V> BiStream<K,V> from(Collection<? extends Map.Entry<? extends K, ? extends V>> entries) Returns aBiStreamof 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 aBiStreamofelements, each transformed to a pair of values withtoKeyandtoValue. -
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 aBiStreamof the elements fromstream, each transformed to a pair of values withtoKeyandtoValue. -
from
-
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 theworkfunction. Theinitialinput is passed toworkfor the first round, after which theincrementfunction is called to determine the input for the next round. This process repeats until theincrementfunction 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 theworkfunction. 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
workfunction. The stream is lazy in thatworkwon'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
-
mapToObj
Returns aStreamconsisting of the results of applyingmapperto each pair in thisBiStream. -
mapToObjIfPresent
public final <T> Stream<T> mapToObjIfPresent(BiFunction<? super K, ? super V, ? extends Optional<? extends T>> mapper) Returns aStreamconsisting of the results of applyingmapperto each pair in thisBiStream. Ifmapperfunction 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 aBiStreamconsisting of the results of applyingkeyMapperandvalueMapperto 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 aBiStreamconsisting of the result pairs of applyingmapperto 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 aBiStreamconsisting of the results of applyingmapperfunction to the pairs in thisBiStream. Ifmapperreturns empty, the pair is discarded.- Since:
- 5.0
-
mapToDouble
-
mapToInt
-
mapToLong
-
mapKeys
Returns aBiStreamof pairs whose keys are the result of applyingkeyMapperto the key of each pair in thisBiStream, and whose values are unchanged. -
mapKeys
-
mapValues
Maps each value to another value of typeV2. -
mapValues
-
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 moredoubles.If a mapped stream is null, an empty stream is used instead.
-
flatMapToInt
Maps a single pair to zero or moreints.If a mapped stream is null, an empty stream is used instead.
-
flatMapToLong
public final LongStream flatMapToLong(BiFunction<? super K, ? super V, ? extends LongStream> mapper) Maps a single pair to zero or morelongs.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 aBiStreamfor 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
-
flatMapKeys
-
mapKeysIfPresent
GivenkeyMappingthat maps the keys of typeKto elements of typeK2, returns aBiStreamof 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 aBiStreamof pairs whose keys are the result of applyingkeyMapperto the key of each pair in thisBiStream, and whose values are unchanged. IfkeyMapperfunction 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 aBiStreamof pairs whose keys are the result of applyingkeyMapperto each pair in thisBiStream, and whose values are unchanged. IfkeyMapperfunction returns empty, the pair is discarded.- Since:
- 4.7
-
flatMapValues
-
flatMapValues
-
mapValuesIfPresent
GivenvalueMappingthat maps values of typeVto result values of typeV2, returns aBiStreamof 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 aBiStreamof pairs whose values are the result of applyingvalueMapperto the value of each pair in thisBiStream, and whose keys are unchanged. IfvalueMapperfunction 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 aBiStreamof pairs whose values are the result of applyingvalueMapperto each pair in thisBiStream, and whose keys are unchanged. IfvalueMapperfunction returns empty, the pair is discarded.- Since:
- 4.7
-
peek
-
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
-
skipValuesIf
-
append
Returns aBiStreamconsisting 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 aBiStreamconsisting of the pairs in this stream, followed by the pairs inmap.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.- Since:
- 8.7
-
append
Returns aBiStreamconsisting of the pairs in this stream, followed by the pair ofkeyandvalue.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
-
values
-
inverse
-
forEach
Performsactionfor each pair in this stream. -
forEachOrdered
Performsactionfor 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
-
skip
-
distinct
-
sortedByKeys
Returns aBiStreamconsisting of the pairs in this stream, in the order produced by applyingcomparatoron the keys of each pair. -
sortedByValues
Returns aBiStreamconsisting of the pairs in this stream, in the order produced by applyingcomparatoron 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 aBiStreamconsisting of the pairs in this stream, in the order produced by applyingcomparatoron the result of applying thesortKeyFunction.- Since:
- 6.6
-
sorted
Returns aBiStreamconsisting of the pairs in this stream, in the order produced by applying thebyKeycomparator on the keys of each pair, and then thebyValuecomparator 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 immutableMapthat 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 typeRthat is the result of collecting the pairs in this stream usingcollector.Please note that any
Collector-returning factory method can be directly "method referenced" asBiCollectorif it accepts twoFunctionparameters 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
BiCollectorsfor some other usefulBiCollectorimplementations. -
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
containerinstance.- 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:
closein 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 aBiStreamconsisting of consecutive groupings from this stream. Consecutive pairs whose key maps to the same group according toclassifierwill 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
classifierwill 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 lazyBiStreamof the consecutive groups of pairs from this stream. Consecutive pairs whose key maps to the same group according toclassifierwill have their values reduced using thegroupReducerfunction.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 aBiStreamconsisting of consecutive groupings from this stream. Consecutive pairs mapping to the same group according toclassifierwill 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
classifierwill 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 lazyStreamof 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
sameGrouppredicate 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
sameGrouppredicate andgroupCollectorallow 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 lazyStreamof 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
sameGrouppredicate 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
sameGrouppredicate andgroupCollectorallow nulls.- Since:
- 5.4
-
groupConsecutiveIf
public final Stream<V> groupConsecutiveIf(BiPredicate<? super K, ? super K> sameGroup, BinaryOperator<V> groupReducer) Returns a lazyStreamof 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
sameGrouppredicate 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
sameGrouppredicate andgroupCollectorallow nulls.- Since:
- 5.4
-
biStream(User::id, users)to createBiStream<UserId, User>, or, usebiStream(users, User::getAccount)to createBiStream<User, Account>.