Type of the items in the stream.
Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>
Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>
Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>
Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>
Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>
Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>
Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>
Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>
Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>
Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>
Overload with tuple types for IStream#chunk(chunkSize: number): IStream<T[]>
Chunks the items into chunks of chunkSize.
stream([1,2,3,4,5]).chunk(2) // => Stream[ [1,2], [3,4], [5] ]
stream([1,2,3,4,5]).chunk(1) // => Stream[ [1], [2], [3], [4], [5] ]
stream([1,2,3,4,5]).chunk(0) // => Stream[]
stream([1,2,3,4,5]).chunk(NaN) // => Stream[]
stream([1,2,3,4,5]).chunk(Infinity) // => Stream[[1,2,3,4,5]]
Size of the produced chunks.
A stream over the chunked items.
Chunks together consecutive items for which the classifier
returns the same value. Equality is checked with ===
.
stream([1,2,3,4,5,6,1]).chunkBy(i => i & 10)
// => Stream[ [1,2], [3,4], [5,6], [1] ]
Type of the returned value of the chunker,
It is passed the item as its first argument and the index as its second. Items are chunked together according to the returned value.
A stream over the chunked items.
Creates an object and incorporates all items into that object.
stream([1,2,3]).collect(Collectors.summarize)
// => Statistic[min:1, max:3, count: 3, sum: 6, average: 2, variance: 0.67]
Type of the intermediate object that incorporates each item in order.
Type of the final collected value.
How to collect the items.
The collected value.
Same as {@link #collect}, but allows specifying the parts of the collector individually.
stream([1,2,3]).collect(() => [], (array, x) => array.push(x), x => new Set(x))
// => Set[1,2,3]
Type of the intermediate value that incorporates each item in order.
Type of the final collected value.
Takes the intermediate objects as its first argument and the current items as its seconds, and incorporates the item into the intermediate value.
Takes the intermediate object with all the items incoporated, and transforms it into the final value.
The final collected value.
Concatenates all given iterables with this stream into one stream of all the items.
stream("foo").concat("bar", "baz")
// => Stream["f", "o", "o", "b", "a", "r", "b", "a", "z"]
A stream over all the items of this stream and the given iterables.
Consumes the given amount of items at a given offset from the start of of this stream, and adds thems to the sink. The items at the start of the stream and the remaining items can be read from the returned stream.
const sink = [];
const s = stream("foobar").consume(sink, 0, 3);
// => sink is now ["f", "o", "o"]
s.join() // => "bar"
const sink2 = [];
const s2 = stream("foobar").consume(sink, 2, 3);
// => sink is now ["o", "b", "a"]
s2.join() // => "for"
stream("foobar").consume(console.log, 0, 3);
// => logs "f", "o", "o"
stream("foobar").consume(console.log, 0, -3);
// => logs nothing
If an array, consmed items are added to the array. Otherwise, the consumer is called with the consumed item.
Where to start consuming items. Defaults to 0
.
Maximum number of items to consume. Defaults to Infinity
.
A stream over the remaining items.
Computes a new value from each successful value or error. If the operation or backup function throws an error, or if no backup is provided, the Try is not successful.
stream("12a").try(JSON.parse).convert(x => 2*x)
// Stream[ Try[value=1], Try[value=2], Try[error="invalidJSON"] ]
Type of the new value.
Mapper that converts each succesful values into the new one.
Optional mapper that converts each error into the new value.
A try-stream with the converted values, or any thrown errors.
Cycles over the elements of this stream the given number of times.
stream([1,2,3]).cycle(NaN) // => Stream[]
stream([1,2,3]).cycle(0) // => Stream[]
stream([1,2,3]).cycle(3) // => Stream[1,2,3,1,2,3,1,2,3]
stream([1,2,3]).cycle().limit(5) // => Stream[1,2,3,1,2]
The number of cycle. If not given, cycles the items endlessly.
A stream with the items of the this stream repeating.
Passes all errors to the given handler and removes them from the stream.
stream(...).try(JSON.parse).discardError().toArray()
// => [json1, json2, ...]
// prints all errors encountered during parsing
For handling the errors. Defaults to console.error
.
A stream with all the errors removed.
Applies all pending operations, ending this stream.
stream([1,2,3]).visit(console.log) // Stream[1,2,3]; prints nothing
stream([1,2,3]).visit(console.log).end() // prints 1,2,3
Note that for the above example, you could also simply use forEach
.
stream([1,2,3]).forEach(console.log) // prints 1,2,3
Determines whether every items matches the given predicate.
stream("fooz").every(x => x < "j") // => false
Test to be performed on the items.
Whether every items matches the given predicate.
Removes all elements from this stream for which the
predicate does not return true
.
stream([4,-4,2,-9]).filter(x => x > 0) // => Stream[4,2]
Testing function returning true
iff the item is to be kept, false
otherwise.
A stream over all items for which the predicate returned true
.
Similar to IStream#filter, but filters out all items not equivalent to the given target. Items are compared to the target by first extracting a key with the given key extractor, and then comparing the keys with the given comparator.
stream(["foo", "bar", "foobar"]).filterBy(x => x.length)
// => Stream["foo", "bar"]
const user1 = {name: "Dave", birth: {day: 5, month: 4, year: 2005}}
const user2 = {name: "Maria", birth: {day: 9, month: 11, year: 2005}}
const user3 = {name: "Odo", birth: {day: 22, month: 7, year: 2004}}
stream([user1, user2, user3]).filterBy(2005, user => user.birth, (lhs,rhs) => lhs.year - rhs.year)
// => Stream[user1, user2]
Target for filterting. All items in the stream not equivalent to the target are removed.
Extracts the key by which equality is determined. Default to identity x => x
.
Comparator for comparing two keys. Defaults to the natural comparator using <
and >
.
A stream over all items whose keys compare equal to the given target.
Searches for the first occurence of an item matching the predicate.
stream(["foo1", "bar,"foo2").find(x => x.startsWith("foo")) // => "foo1"
Test to be performed on the items. It is passed the current item and the current index.
The item iff found, undefined
otherwise.
Searches for the first occurence of an item matching the predicate,
and returns the index, or -1
otherwise.
stream(["foo1", "bar, "foo2").find(x => x.startsWith("foo")) // => 0
Test to be performed on the items. It is passed the current item and the current index.
The index iff the item was found, -1
otherwise.
Returns the first item and closes the stream.
stream("foo").first() // => "f"
stream("").first() // => undefined
const s = stream("foobar");
s.first()
s.first() // => Error
The item at the first position, or undefined if empty.
Computes a new value from each successful value or error. If the operation or backup function throws an error, or if no backup is provided, the ITry is not successful. Similar to {@link #flatConvert}, but the operation and backup handlers return a ITry directly.
stream(["\"1\"", "\"1.5\""]).try(JSON.parse).convert(x => Try.of(() => parseIntSafe(x)))
// Stream[ Try[value=1], Try[error="not an int" ]
Type of the new value.
Mapper that converts each succesful values into a ITry of the new value.
Optional mapper that converts each error into a ITry of the new value.
A try-stream with the converted values, or any thrown errors.
Applies the mapping function to each item and return a stream
over all the mapped iterables.
This is equivalent to concat(map(mapper))`
.
stream(["foo","bar"]).flatMap(x => x)
// => Stream["f", "o", "o", "b", "a", "r"]
stream(["[1]","[2,3]","[4,]"]).try(JSON.parse).flatMap(x=>x.stream())
// => Stream[ [1], [2, 3] ]
Type of the elements in the produced stream.
Mapping function taking each item and producing a new stream or iterable.
A stream over all the items of the iterables produced by the mapper.
Passes each item of this stream to the given consumer.
stream([1,2,3]).forEach(console.log); // prints 1,2,3
A callback that receives each item of this stream in order.
Passes each successful value or error to the given handler.
stream(...).try(JSON.parse).forEachResult(
json => { process(...) },
error => console.error(error)
)
Handler that is passed all successful values.
Optional handler that is passed all errors. Defaults to console.error
.
This returns a stream that leaves the original stream open and iterable. If the underlying iterable is an array, set, map or string etc, it simpy reuses that iterable, otherwise it buffers the items temporarily.
function * foo() {
return 1;
return 2;
return 3;
}
const transientStream = stream(foo());
transientStream.toArray() // => [1,2,3]
transientStream.toArray() // => Error: Stream was consumed already.
const persistentStream = stream(foo())
persistentStream.fork().toArray() // => [1,2,3]
persistentStream.fork().toArray() // => [1,2,3]
persistentStream.toArray() // => [1,2,3]
persistentStream.fork() // => Error: Stream was consumed already.
Note that buffering takes place on-demand, so the following will not enter an infinite loop:
// Create a stream with an unlimited amount of items.
const stream = TypesafeStreamFactory.generate(Math.random, Infinity);
// Fork the stream first, then limit to a finite number of items.
// Items already produced are not recomputed.
stream.fork().limit(3).toArray() // => [0.28, 0.14, 0.97]
stream.fork().limit(2).toArray() // => [0.28, 0.14]
stream.fork().limit(4).toArray() // => [0.28, 0.14, 0.97, 0.31]
A forked stream that leaves the original stream usable.
Splits the items into several groups, according to the given classifier.
stream(["a", "foo", "is", "some", "buzz"]).group(x => x.length) // => Map [ 1 => ["a"], 2 => ["is"], 3 => "is", 4 => ["some", "buzz"] ]
Returns the group for each item.
A map with the groups as keys and arrays as values, containing all the items for that group.
Determines whether this stream contains the given item.
Equivalence is checked with ===
. This is
equivalent to `
stream(...).some(x => x === object)`.
stream("foobar").has("o") // => true
Whether the given object is contained in this stream.
Applies the given test to the successful values and produces an error for those that do not match.
stream("12a").try(JSON.parse).include(x => x < 2)
// => Stream[ Try[value=1], Try[error="does not match"], Try[error="invalid JSON"] ]
Test successful values need to pass for includsion.
A try-stream with all successful values passing the test.
Adds the index to each element of this stream. The index starts at 0.
stream(["foo", "bar"]).index().toMap(({value}) => value, ({index}) => index})
// => Map<"foo" => 0, "bar" => 1>
A stream with each item being an array consisting of the item's index and the item itself. The index starts at 0.
Determines whether this stream contains no items. This consumes at most one item from the stream and works with infinite streams.
This method leaves the original stream intact, ie. you can call other methods on the original stream and get the same result as if this methods had not been called.
stream([]).isEmpty() // => true
stream([1,2,3]).isEmpty() // => false
const s = stream([1,2,3]);
if (!s.isEmpty()) {
// This works and includes all three items because
// isEmpty left the stream intact.
s.map(x=>x*x).toArray() // => [2,4,6]
}
True iff this stream contains no items.
Determines whether the number of items in this stream is at least lower
and at most upper
.
This method only consumes as many elements from the stream as necessary and may be used with
infinite stream. Using stream.size() === 0
would force an endless iteration of all its item.
This method leaves the original stream intact, ie. you can call other methods on the original stream and get the same result as if this methods had not been called.
stream([1,2,3]).isSizeBetween(0, 3) // => true
stream([1,2,3]).isSizeBetween(1, 3) // => true
stream([1,2,3]).isSizeBetween(3, 3) // => true
stream([1,2,3]).isSizeBetween(3, 4) // => true
stream([1,2,3]).isSizeBetween(2, Infinity) // => true
stream([1,2,3]).isSizeBetween(-4, 2) // => false
stream([1,2,3]).isSizeBetween(4, 9) // => false
stream([1,2,3]).isSizeBetween(1, 2) // => false
stream([1,2,3]).isSizeBetween(0) // => true
stream([1,2,3]).isSizeBetween(1) // => true
stream([1,2,3]).isSizeBetween(3) // => true
stream([1,2,3]).isSizeBetween(4) // => false
stream([]).isSizeBetween(0, 0) // => true
stream([]).isSizeBetween(1, 3) // => false
stream([]).isSizeBetween() // => true
stream([1,2,3]).isSizeBetween() // => true
stream([]).isSizeBetween(NaN) // => false
stream([1,2,3]).isSizeBetween(NaN) // => false
stream([]).isSizeBetween(NaN, NaN) // => false
stream([1,2,3]).isSizeBetween(NaN, NaN) // => false
Minimum number of items allowed. Defaults to 0
.
Maximum number of items allowed. Defaults to Infinity
.
True iff this stream contains the specified number of items.
Joins every time with the given delimiter, optionally prepending a prefix and appending a suffix to the output.
stream([1,2,3]).join(",", "[", "]") // => "[1,2,3]"
String inserted between the items. Defaults to the empty string.
String prepended to the joined string. Defaults to the empty string.
String appended to the joined string. Defaults to the empty string.
A string consisting of the prefix, the items joined with the delimiter, and the suffix.
Returns the last item.
stream("foo").last() // => "o"
stream("").last() // => undefined
The item at the last position, or undefined if empty.
Limits the stream to at most the given number of elements.
stream([1,2,3,4,5,6]).limit(NaN) // => Stream[1,2,3,4,5,6]
stream([1,2,3,4,5,6]).limit(0) // => Stream[1,2,3,4,5,6]
stream([1,2,3,4,5,6]).limit(3) // => Stream[1,2,3]
A stream with at most the given number of items.
Transform each element to another element of a possibly different type.
stream([0,1,2,3]).map(x => 2 * x) // => Stream[0,2,4,6]
Type of the elements in the produced stream.
A function taking each item of this stream and transforms it into another item.
A stream over the mapped elements.
Computes the maxmimum of the items.
stream([6,2,3,9,4]).max() // => 9
stream(["foo", "bar", "I"]).max(Comparators.byField("length")) // => "foo"
stream([]).max() // => undefined
How two items are compared. Defaults to the natural order, ie. by using <
and >
.
The largest item. If there are multiple largest items, returns the first. undefined
iff this stream is empty.
Computes the maximum of the items, as determined by the given sort key.
stream(["foo","foobar", "gg"]).maxBy(x => x.length)
// => "gg"
Takes an item and produces the key by which the maximum is determined.
The smallest item, or undefined
iff there are no items.
Computes the minimum of the items.
stream([3,2,9,4]).min() // => 9
stream(["foo", "bar", "I"].min(Comparators.byField("length")) // => "I"
stream([]).min() // => undefined
How two items are compared. Defaults to the natural order, ie. by using <
and >
.
The smallest item. If there are multiple smallest items, returns the first. undefined
iff this stream is empty.
Computes the minimum of the items, as determined by the given sort key.
stream(["foo","foobar", "gg"]).minBy(x => x.length)
// => "gg"
Takes an item and produces the key by which the minimum is determined.
The smallest item, or undefined
iff there are no items.
Determines whether no item matches the given predicate. This
is equivalent to !stream.some(predicate)
.
stream("fooz").none(x => x === "o") // => false
Test to be performed on each item.
Whether no item matches the given predicate.
Returns the items at the n-th position.
stream("foo").nth(1) // => "f"
stream("foo").nth(3) // => undefined
The position of the item to get.
The item at the given position, or undefined if not found.
Calls the given error handler for all errors once the stream is consumed.
stream("12a").try(JSON.parse).onError(console.warn).end()
// => Stream[ Try[value=1], Try[value=2], Try[error="invalid JSON"] ]
// Warns about errors once the stream is consumed.
This try-stream.
Calls the given success handler for all successful values and the given error handler, if present, for all errors.
stream("12a").try(JSON.parse).onSuccess(console.info, console.warn)
// => Stream[ Try[value=1], Try[value=2], Try[error="invalid JSON"] ]
// Informs about success and warns about errors once the stream is consumed.
Handler called with successful values.
Handler called with errors. If not present, it is not called.
This try-stream.
Returns a stream with each items being either the successful value of the ITry or the given backup value.
stream("12a").try(JSON.parse).orElse(undefined)
// Stream[1,2,undefined]
A default value for errors.
A stream with either the successful value or the backup value.
Applies the backup handler to each error, producing a value of the same type as the succesful value of this try-stream. If the handler throws, the resulting ITry is not successful.
stream(["https://...", "https://..."]).try(GetSync).orTry(e => e.status)
// Stream[ Try[value="response"], Try[value="Not found"] ]
Handler that takes each error and produces a backup value.
A try-stream with all erronous values replaced with the backup values.
Splits the items into two groups according to the given discriminator.
stream([-3,2,9,-4]).partition(x => x > 0) // => { false: [-3,-4], true: [2,9]}
Partitions each item into one of two groups by returning true
of false
.
An object containing the partitioned items.
Converts each item to a promise and returns a promise that is resolved with a stream of results when all of the created Promises resolve, or rejected when any Promise is rejected.
stream([1,2,3])
.promise(id => fetch(`/user/${id}`))
.then(s => s.forEach(renderUser))
.catch(console.error)
// Calls the renderUser method with the Response for each user request.
Type of the item of the promises.
Takes each item and creates a promise.
A promise that resolves when all promises resolve; or is rejected when any promise is rejected.
Coalesces all items into one value.
stream([1,2,3]).reduce((sum,x) => sum + x, 10) // => 16
Type of the reduced value.
Takes the current reduced value as its first argument and the current item as its second, combines the item with the current reduced value, and returns that value.
The initial value of the reduction.
The reduced value, or the initial value iff this stream is empty.
Similar to reduceSame, but reduces to items of the same type as the items and thus does not require an explicit initial value.
stream([1,2,3]).reduceSame((sum,x) => sum + x) // => 6
Takes the current reduced value as its first argument and the current item as its second, combines the item with the current reduced value, and returns that value.
The reduced value, or undefined iff the stream is empty.
Reverses the order of the items.
Note that the items need to be saved temporarily, so that this does not work with unlimited streams, as the last item needs to be accesed first.
This method might create a new array, but if it does, calling toArray
on
the returned stream will return that array instead of allocating a new array.
stream([1,2,3]).reverse() // => Stream[3,2,1]
stream(factory.step(Infinity)).reverse() // hangs
A stream with the items in reversed order.
Returns the first item and keeps the stream open. The remaining items can still be read from the stream.
stream("foo").shift() // => "f"
stream("").shift() // => undefined
const s = stream("foobar");
s.shift() // => "f"
s.shift() // => "o"
s.shift() // => "o"
s.join() // => "bar"
The item at the first position, or undefined if empty.
Counts the items.
stream([1,2,3]).count() // => 3
The number of items in this stream.
Discards the given number of items from this stream.
stream([1,2,3,4,5,6]).skip(3) // => Stream[4,5,6]
How many items to skip. Default to Infinity
.
A stream with the given number of items skipped.
Returns the items from the startOffset
up to, but not including, the endOffset
.
This leaves the stream unchanged, all items are still available for further
chaining.
const s = stream("foobar");
s.slice(0, 3); // => ["f", "o", "o"]
s.join() // => "foobar"
const s2 = stream("foobar");
s.slice(2, 5); // => ["o", "b", "a"]
s.join() // => "forbar"
// special cases
stream("foo").slice(0, 0) // => []
stream("foo").slice(3, 2) // => []
stream("foo").slice(0, 2.5) // => ["f", "o"]
stream("foo").slice(0.5, 2) // => ["f", "o"]
stream("foo").slice(-5, 2) // => ["f", "o"]
stream("foo").slice(0, Infinity) // => ["f", "o", "o"]
stream("foo").slice(Infinity, 9) // => []
stream("foo").slice(0, NaN) // => []
stream("foo").slice(NaN, 2) // => []
stream("foo").slice(NaN, NaN) // => []
factory.generate(Math.random).slice(Infinity, Infinity) // => []
Position (inclusive) at which to start removing items from this stream. Default to 0
.
Position (not inclusive) at which to stop removing items from this stream. Defaults to Infinity
.
The items in this stream from startOffset
up to, but not including, endOffset
.
Determines whether at least one items matches the given predicate.
stream("fooz").some(x => x < "j") // => true
Test to be performed on the items.
Whether some (at least one) item matches the given predicate.
Sorts the items according to the given comparator.
This method might create a new array, but if it does, calling toArray
on
the returned stream will return that array instead of allocating a new array.
stream(["foobar", "a", "bar").sor(Comparators.byField("length")]
// => Stream["a", "bar", "foobar"]
How to sort the items. Default to the natural order, ie. by using <
and >
.
A stream with the items in sorted order.
Similar to IStream#sort, but sorts items by comparing them according to the given key extractor and comparator. For each item, a key is extracted, two items are then compared by comparing theirs keys with the given comparator.
This method might create a new array, but if it does, calling toArray
on
the returned stream will return that array instead of allocating a new array.
stream(["foo", "foobar", "bar"]).sortBy(x => x.length)
// => Stream["foo", "bar", "foobar"]
const user1 = {name: "Dave", birth: {day: 5, month: 4, year: 1990}}
const user2 = {name: "Maria", birth: {day: 9, month: 11, year: 2005}}
const user3 = {name: "Odo", birth: {day: 22, month: 7, year: 2004}}
stream([user1, user2, user3]).filterBy(user => user.birth, (lhs,rhs) => lhs.year - rhs.year)
// => Stream[user1, user3, user1]
Extracts the key by which the sort order is determined. Default to identity x => x
.
Comparator for comparing two keys. Defaults to the natural comparator using <
and >
.
Extracts (removes) and returns at most maxAmount
items of this stream, starting
at the given start position. All items up to the starting point and the
remaining items are left in this stream and can still be read from it.
const s = stream("foobar");
s.splice(0, 3); // => ["f", "o", "o"]
s.join() // => "bar"
const s2 = stream("foobar");
s.splice(2,3); // => ["o", "b", "a"]
s.join() // => "for"
// special cases
stream("foo").splice(0, 0) // => []
stream("foo").splice(0, Infinity) // => ["f", "o", "o"]
stream("foo").splice(Infinity, 9) // => []
stream("foo").splice(0, NaN) // => []
stream("foo").splice(NaN, 2) // => []
stream("foo").splice(NaN, NaN) // => []
factory.generate(Math.random).splice(Infinity, 0) // => []
Position at which to start removing items from the stream. Default to 0
.
Maximum number if items to read from this stream. Defaults to Infinity
.
At most maxAmount
items from the given start position of this stream.
Sums all items arithmetically. If there are no items
in the stream, returns NaN
.
stream([]).sum() // => NaN
stream([1,2,3]).sum() // => 6
stream(["I", "of", "Borg"]).sum(x => x.length) // => 7
The sum of the items.
Creates an array with the items of this stream. If the underlying iterable is an array, returns that array instead of creating a new array.
stream("foobar").toArray()
// => ["f", "o", "o", "b", "a", "r"]
Iff true, always creates a new array. Otherise, reuses existing array when possible.
An array with the items.
Hook for JSON.stringify. Returns the items of this stream as an array. Note that this terminates the stream, any subsequent operations on the stream will fail.
stream("foo").toJSON()
// => ["f", "o", "o"]
JSON.stringify(stream("foo"))
// => '["f","o","o"]'
An array with the items of this stream, in the order they are encountered.
Creates a map from the items of this stream. When two items have the same key, the optional merge function is called with the two items and the result of the merge function is used as the value for that key. If no merge function is given, the value of the item encountered first is taken.
stream(["foo", "bar"]).toMap(x => x, x => x.length)
// => Map[ "foo" => 3, "bar" => 3 ]
const data = [{id: 0, name: "foo"}, {id: 0, name: "bar"}];
stream(data).toMap(x => x.id, x => x.name)
// => Map[ 0 => "bar" ]
stream(data).toMap(x => x.id, x => x.name, (name1, name2) => name1 + "," + name2)
// => Map[ 0 => "foo,bar" ]
Type of the map's keys.
Type of the map's values.
Transforms an item into the map key to be used.
Transforms an item into the value used for the corresponding key.
A merge function called when two items map to the same key and returns the merged value. Called with two items having the same key, the first argument is the item encountered first in the stream.
A map with all the mapped key-value-pairs of the items.
Creates a set with the items of this stream. If the underlying iterable is a set, returns that set instead of creating a new set.
stream("foobar").toSet()
// => Set["f", "o", "b", "a", "r"]
Iff true, always creates a new set. Otherwise, reuses existing set when possible.
A set with the items.
Maps each item to the result of the given operation, wrapped in a ITry for error handling.
stream(["1","7","7a"])
.try(SON.parse)
.discardError(console.error)
.toArray();
// => ["success", "success", "error"]
Type of the result of the operation.
Takes each item and returns a mapped value, or throws an Error
.
A stream with the mapped values and additional methods for handling errors.
Passes this stream to the the operation and returns its result, wrapped in a ITry in case the operation throws an error. Usually used for performing a terminal operation with error handling on the stream.
stream([1,2,3]).tryCompute(s => s.sum(item => {throw new Error()}))
// => Try[success=false]
Type of the value produced by the operation.
Takes this stream and returns value. If it throws an error, the resulting ITry is not successful.
The result of the operation, wrapped in a ITry for encapsulating thrown errors.
Same as {@link #end}, but encapsulates any errors thrown. Applies all pending operation to the pipeline.
// prints 1,2,3
stream([1,2,3]).visit(console.log).tryEnd()
The encapsulated error, if any was thrown.
Filters all elements that are considered equal according to the given comparator. If two items are equal, the first one encountered is included in the resulting stream. Consider using {@link #uniqueBy} if possible for better performance.
stream([4,1,3,4,1,3,1,9]).unique()
// => Stream[4,1,3,9]
stream({id:4},{id:2},{id:4]}).unique((x,y) => x.id - y.id)
// => Stream[ {id:4}, {id:2} ]
Takes two items and returns 0 if they are equal. Defaults to taking determining equality by ===
.
A stream with all duplicates removed.
Similar to {@link #unique}, but allows for a custom key to
be specified, according to which uniqueness is determined.
If two items compare equal, the item encountered first in the
stream is taken. If items with the same key need to be merged,
consider using stream.collect(Collectors.toSet(merger))
.
stream([4,1,3,4,1,3,1,9]).distinct()
// => Stream[4,1,3,9]
stream({id:4},{id:2},{id:4]}, customer => customer.id).distinct()
// => Stream[ {id:4}, {id:2} ]
Returns a key for each item. Items with duplicate keys are removed. Defaults to taking the item itself as the key.
A stream with all duplicates removed.
Calls the given consumer once for each item. Note that the consumer is not called before the stream is consumed by some terminal operation.
stream([1,2,3]).visit(console.log)
// => Stream[1,2,3]
// prints `1,2,3` once the stream is consumed.
Callback taking each item.
A stream with the same items as this stream.
Produces a stream over tuples of consisting of an item of the given iterable;
and the corresponding item of the other iterable.
If one of the iterables is longer, the shorter one is
appended with undefined
.
stream(["foo", "bar"].zip([3, 4])
// => Stream[ ["foo",3], ["bar", 4] ]
stream(["foo", "bar"]).zip([3, 4]).toMap(x=>x[0], x=>x[1])
// => Map[ "foo" => 3, "bar" => 4] ]
Other iterable to be zipped to this stream.
A stream over all the produced tuples.
Produces a stream over tuples of consisting of an item of this stream and
the corresponding items of the other iterables.
If any of the iterables has a different length than the others,
the shorter ones appended with undefined
to the length of the longest.
stream("ab").zipSame(["cd", "ef"])
// => Iterable[ ["a","c", "d"], ["b", "d", "f"] ]
stream("abc").zipSame(["d", "ef"])
// => Iterable[ ["a","d", "e"], ["b", undefined, "f"], ["c", undefined, undefined] ]
stream("fb").zipSame(["oa","or"]).map(x=>x.map(String).join("")).join("").toArray()
// => "foobar"
Other iterable to be zipped to the given iterable.
A stream over al the produced tuples.
Generated using TypeDoc
Contains several convenience methods for easier error handling with ITry. A try-stream is created by using the {@link Stream.try} method.
`
javascript stream(input).try(operation).orElse(0)// The above is equivalent to the following:
stream(input).map(operation).map(x => x.orElse(0))
`