Interface Traversable<T>
- Type Parameters:
T- the type of elements contained in this Traversable
- All Known Subinterfaces:
BitSet<T>,IndexedSeq<T>,Iterator<T>,LinearSeq<T>,List<T>,Map<K,,V> Multimap<K,,V> Seq<T>,Set<T>,SortedMap<K,,V> SortedMultimap<K,,V> SortedSet<T>,Stream<T>,Tree<T>
- All Known Implementing Classes:
Array,CharSeq,HashMap,HashMultimap,HashSet,LinkedHashMap,LinkedHashMultimap,LinkedHashSet,List.Cons,List.Nil,PriorityQueue,Queue,Stream.Cons,Stream.Empty,Tree.Empty,Tree.Node,TreeMap,TreeMultimap,TreeSet,Vector
Iterable.iterator() and may vary across calls.
This interface provides operations for:
- Basic access: querying elements, length, head/tail, and emptiness.
- Iteration: indexed traversal, sliding windows, and grouping.
- Numeric computations: sum, product, min/max, and averages.
- Reduction and folding: folding, reducing, and string representation.
- Selection and slicing: take/drop, filtering, partitioning, and sub-sequencing.
- Testing: uniqueness, order, distinctness, and sequence properties.
- Transformation: mapping, flat-mapping, scanning, zipping, and deduplication.
Implementations may be lazy or strict and may support infinite sequences.
- Author:
- Daniel Dietrich, Grzegorz Piwowarek
-
Method Summary
Modifier and TypeMethodDescriptionGroups elements by a unique key extracted from each element.average()Computes the average of the elements, assuming they are of typeNumber.<R> Traversable<R> collect(@NonNull PartialFunction<? super T, ? extends R> partialFunction) Applies aPartialFunctionto all elements that are defined for it and collects the results.default booleancontainsAll(@NonNull Iterable<? extends T> elements) Checks whether thisTraversablecontains all elements from the given iterable.default intCounts the number of elements that satisfy the given predicate.distinct()Returns a newTraversablecontaining the elements of this instance with all duplicates removed.distinctBy(@NonNull Comparator<? super T> comparator) Returns a newTraversablecontaining the elements of this instance without duplicates, as determined by the givencomparator.<U> Traversable<T> distinctBy(@NonNull Function<? super T, ? extends U> keyExtractor) Returns a newTraversablecontaining the elements of this instance without duplicates, based on keys extracted from elements usingkeyExtractor.drop(int n) Returns a newTraversablewithout the firstnelements, or an empty instance if this contains fewer thannelements.dropRight(int n) Returns a newTraversablewithout the lastnelements, or an empty instance if this contains fewer thannelements.Returns a newTraversablestarting from the first element that satisfies the givenpredicate, dropping all preceding elements.Returns a newTraversablestarting from the first element that does not satisfy the givenpredicate, dropping all preceding elements.booleanDetermines whether this collection is equal to the given object.default booleanexistsUnique(@NonNull Predicate<? super T> predicate) Checks whether there is exactly one element in this traversable for which the given predicate holds.Returns a new traversable containing only the elements that satisfy the given predicate.Returns the first element that satisfies the given predicate.Returns the last element that satisfies the given predicate.<U> Traversable<U> Transforms each element of this Traversable into anIterableof elements and flattens the resulting iterables into a single Traversable.default <U> UfoldLeft(U zero, @NonNull BiFunction<? super U, ? super T, ? extends U> f) Folds the elements of this structure from the left, starting with the givenzerovalue and successively applying thecombinefunction to each element.<U> UfoldRight(U zero, @NonNull BiFunction<? super T, ? super U, ? extends U> f) Folds the elements of this structure from the right, starting with the givenzerovalue and successively applying thecombinefunction to each element.default voidforEachWithIndex(@NonNull ObjIntConsumer<? super T> action) Performs the given action on each element of this Traversable along with its index.default Tget()Returns the first element of thisTraversablein iteration order.<C> Map<C, ? extends Traversable<T>> Groups elements of thisTraversablebased on a classifier function.Iterator<? extends Traversable<T>> grouped(int size) Splits thisTraversableinto consecutive blocks of the given size.booleanIndicates whether thisTraversablehas a known finite size.inthashCode()Returns the hash code of this collection.head()Returns the first element of this non-emptyTraversable.Returns the first element of thisTraversableas anOption.init()Returns all elements of this Traversable except the last one.default Option<? extends Traversable<T>> Returns all elements of this Traversable except the last one, wrapped in anOption.default booleanIndicates whether this Traversable may contain only distinct elements.default booleanisEmpty()Checks if this Traversable contains no elements.default booleanIndicates whether this Traversable is ordered according to its natural or specified order.default booleanIndicates whether the elements of this Traversable appear in encounter (insertion) order.default booleanIndicates that this Traversable may contain multiple elements.booleanChecks if this Traversable can be traversed multiple times without side effects.iterator()last()Returns the last element of this Traversable.Returns the last element of this Traversable as anOption.intlength()Returns the number of elements in this Traversable.<U> Traversable<U> Transforms the elements of this Traversable to a new type, preserving order if defined.default <U> Traversable<U> mapTo(U value) Maps the underlying value to another fixed value.default Traversable<Void> Maps the underlying value to Voidmax()Returns the maximum element of this Traversable according to the natural order of its elements.maxBy(@NonNull Comparator<? super T> comparator) Returns the maximum element of this Traversable according to the given comparator.default <U extends Comparable<? super U>>
Option<T> Returns the element of this Traversable whose mapped value, according to the given function, is maximal.min()Returns the minimum element of this Traversable according to its natural order in O(n).minBy(@NonNull Comparator<? super T> comparator) Returns the minimum element of this Traversable according to a given comparator.default <U extends Comparable<? super U>>
Option<T> Returns the element of this Traversable whose mapped value is minimal according to natural order.default CharSeqConcatenates the string representations of all elements in this Traversable.default CharSeqmkCharSeq(CharSequence delimiter) Concatenates the string representations of all elements in this Traversable, separated by a delimiter.default CharSeqmkCharSeq(CharSequence prefix, CharSequence delimiter, CharSequence suffix) Concatenates the string representations of all elements in this Traversable with a prefix, delimiter, and suffix.default StringmkString()Concatenates the string representations of all elements in this Traversable.default StringmkString(CharSequence delimiter) Concatenates the string representations of all elements in this Traversable, separated by a delimiter.default StringmkString(CharSequence prefix, CharSequence delimiter, CharSequence suffix) Concatenates the string representations of all elements in this Traversable with a prefix, delimiter, and suffix.static <T> Traversable<T> narrow(Traversable<? extends T> traversable) Narrows aTraversable<? extends T>toTraversable<T>with a type-safe cast.default booleannonEmpty()Checks if thisTraversablecontains at least one element.Returns thisTraversableif it is non-empty; otherwise, returns the given alternative.Returns thisTraversableif it is non-empty; otherwise, returns the result of evaluating the given supplier.Tuple2<? extends Traversable<T>, ? extends Traversable<T>> Splits thisTraversableinto two partitions according to a predicate.Performs the givenactionon the first element if this is an eager implementation.default Numberproduct()Calculates the product of the elements in thisTraversable.default TreduceLeft(@NonNull BiFunction<? super T, ? super T, ? extends T> op) Reduces the elements of this Traversable from the left using the given binary operation.reduceLeftOption(@NonNull BiFunction<? super T, ? super T, ? extends T> op) Reduces the elements of this Traversable from the left using the given binary operation, returning the result wrapped in anOption.default TreduceRight(@NonNull BiFunction<? super T, ? super T, ? extends T> op) Reduces the elements of this Traversable from the right using the given binary operation.reduceRightOption(@NonNull BiFunction<? super T, ? super T, ? extends T> op) Reduces the elements of this Traversable from the right using the given binary operation, returning the result wrapped in anOption.default Traversable<T> Returns a new traversable containing only the elements that do not satisfy the given predicate.Replaces the first occurrence ofcurrentElementwithnewElement, if it exists.replaceAll(T currentElement, T newElement) Replaces all occurrences ofcurrentElementwithnewElement.Retains only the elements from this Traversable that are contained in the givenelements.Computes a prefix scan of the elements of this Traversable.<U> Traversable<U> scanLeft(U zero, @NonNull BiFunction<? super U, ? super T, ? extends U> operation) Produces a collection containing cumulative results of applying the operator from left to right.<U> Traversable<U> scanRight(U zero, @NonNull BiFunction<? super T, ? super U, ? extends U> operation) Produces a collection containing cumulative results of applying the operator from right to left.default Tsingle()Returns the single element of this Traversable.Returns the single element of this Traversable as anOption.default intsize()Returns the number of elements in this Traversable.Iterator<? extends Traversable<T>> Partitions thisTraversableinto consecutive non-overlapping windows according to a classification function.Iterator<? extends Traversable<T>> sliding(int size) Slides a window of a givensizeover thisTraversablewith a step size of 1.Iterator<? extends Traversable<T>> sliding(int size, int step) Slides a window of a specificsizewith a givenstepover thisTraversable.Tuple2<? extends Traversable<T>, ? extends Traversable<T>> Splits thisTraversableinto a prefix and remainder according to the givenpredicate.default Spliterator<T> default Numbersum()Calculates the sum of the elements in thisTraversable.tail()Returns a newTraversablewithout its first element.default Option<? extends Traversable<T>> Returns a newTraversablewithout its first element as anOption.take(int n) Returns the firstnelements of thisTraversable, or all elements ifnexceeds the length.takeRight(int n) Returns the lastnelements of thisTraversable, or all elements ifnexceeds the length.Takes elements from thisTraversableuntil the given predicate holds for an element.Takes elements from thisTraversablewhile the given predicate holds.<T1,T2> Tuple2 <? extends Traversable<T1>, ? extends Traversable<T2>> Unzips the elements of thisTraversableby mapping each element to a pair and splitting them into two separateTraversablecollections.<T1,T2, T3>
Tuple3<? extends Traversable<T1>, ? extends Traversable<T2>, ? extends Traversable<T3>> Unzips the elements of thisTraversableby mapping each element to a triple and splitting them into three separateTraversablecollections.<U> Traversable<Tuple2<T, U>> Returns aTraversableformed by pairing elements of thisTraversablewith elements of anotherIterable.<U> Traversable<Tuple2<T, U>> Returns aTraversableformed by pairing elements of thisTraversablewith elements of anotherIterable, filling in placeholder elements when one collection is shorter than the other.<U,R> Traversable <R> zipWith(@NonNull Iterable<? extends U> that, BiFunction<? super T, ? super U, ? extends R> mapper) Returns aTraversableby combining elements of thisTraversablewith elements of anotherIterableusing a mapping function.Zips thisTraversablewith its indices, starting at 0.<U> Traversable<U> zipWithIndex(@NonNull BiFunction<? super T, ? super Integer, ? extends U> mapper) Zips thisTraversablewith its indices and maps the resulting pairs using the provided mapper.Methods inherited from interface io.vavr.collection.Foldable
fold, reduce, reduceOptionMethods inherited from interface io.vavr.Value
collect, collect, contains, corresponds, eq, exists, forAll, forEach, getOrElse, getOrElse, getOrElseThrow, getOrElseTry, getOrNull, isAsync, isLazy, out, out, stderr, stdout, stringPrefix, toArray, toCharSeq, toCompletableFuture, toEither, toEither, toInvalid, toInvalid, toJavaArray, toJavaArray, toJavaArray, toJavaCollection, toJavaList, toJavaList, toJavaMap, toJavaMap, toJavaMap, toJavaOptional, toJavaParallelStream, toJavaSet, toJavaSet, toJavaStream, toLeft, toLeft, toLinkedMap, toLinkedMap, toLinkedSet, toList, toMap, toMap, toOption, toPriorityQueue, toPriorityQueue, toQueue, toRight, toRight, toSet, toSortedMap, toSortedMap, toSortedMap, toSortedMap, toSortedSet, toSortedSet, toStream, toString, toTree, toTree, toTry, toTry, toValid, toValid, toValidation, toValidation, toVector
-
Method Details
-
narrow
Narrows aTraversable<? extends T>toTraversable<T>with a type-safe cast.This is safe because immutable or read-only collections are covariant in their element type.
- Type Parameters:
T- the element type of the resultingTraversable- Parameters:
traversable- theTraversableinstance to narrow- Returns:
- the same
traversableinstance with typeTraversable<T>
-
arrangeBy
Groups elements by a unique key extracted from each element.Returns
Noneif any key occurs more than once; otherwise, returns aMapwhere each key is associated with its corresponding element.- Type Parameters:
K- the type of keys- Parameters:
getKey- a function to extract a key from each element- Returns:
- an
Optioncontaining theMapof elements by key, orNoneif keys are not unique - Throws:
NullPointerException- ifgetKeyis null- See Also:
-
average
Computes the average of the elements, assuming they are of typeNumber.If the elements are not numeric, an
UnsupportedOperationExceptionis thrown.Examples:
List.empty().average() // = None List.of(1, 2, 3).average() // = Some(2.0) List.of(1.0, 1e100, 2.0, -1e100).average() // = Some(0.75) List.of(1.0, Double.NaN).average() // = NaN List.of("apple", "pear").average() // throwsUnlike Java's
DoubleStream.average()which uses the Kahan summation algorithm, Vavr uses Neumaier's modification of Kahan's algorithm for improved numerical accuracy.- Returns:
Some(average)if the sequence has elements, otherwiseNone- Throws:
UnsupportedOperationException- if any element is not numeric
-
collect
Applies aPartialFunctionto all elements that are defined for it and collects the results.For each element in iteration order, the function is first tested:
IfpartialFunction.isDefinedAt(element)true, the element is mapped to typeR:R newElement = partialFunction.apply(element)Note: If this
Traversableis ordered (i.e., extendsOrdered), the caller must ensure that the resulting elements are comparable (i.e., implementComparable).- Type Parameters:
R- the type of elements in the resultingTraversable- Parameters:
partialFunction- a function that may not be defined for all elements of this traversable- Returns:
- a new
Traversablecontaining the results of applying the partial function - Throws:
NullPointerException- ifpartialFunctionis null
-
containsAll
Checks whether thisTraversablecontains all elements from the given iterable.Equivalent to testing each element individually:
but implemented efficiently without recursion.elements.isEmpty() ? true : contains(elements.head()) && containsAll(elements.tail())- Parameters:
elements- anIterableof elements to check for containment- Returns:
trueif all elements are present,falseotherwise- Throws:
NullPointerException- ifelementsis null
-
count
Counts the number of elements that satisfy the given predicate.- Parameters:
predicate- a condition to test each element- Returns:
- the number of elements matching the predicate (always >= 0)
- Throws:
NullPointerException- ifpredicateis null
-
distinct
Traversable<T> distinct()Returns a newTraversablecontaining the elements of this instance with all duplicates removed. Element equality is determined usingequals.- Returns:
- a new
Traversablewithout duplicate elements
-
distinctBy
Returns a newTraversablecontaining the elements of this instance without duplicates, as determined by the givencomparator.- Parameters:
comparator- a comparator used to determine equality of elements- Returns:
- a new
Traversablewith duplicates removed - Throws:
NullPointerException- ifcomparatoris null
-
distinctBy
Returns a newTraversablecontaining the elements of this instance without duplicates, based on keys extracted from elements usingkeyExtractor.The first occurrence of each key is retained in the resulting sequence.
- Type Parameters:
U- the type of key- Parameters:
keyExtractor- a function to extract keys for determining uniqueness- Returns:
- a new
Traversablewith duplicates removed based on keys - Throws:
NullPointerException- ifkeyExtractoris null
-
drop
Returns a newTraversablewithout the firstnelements, or an empty instance if this contains fewer thannelements.- Parameters:
n- the number of elements to drop- Returns:
- a new instance excluding the first
nelements
-
dropRight
Returns a newTraversablewithout the lastnelements, or an empty instance if this contains fewer thannelements.- Parameters:
n- the number of elements to drop from the end- Returns:
- a new instance excluding the last
nelements
-
dropUntil
Returns a newTraversablestarting from the first element that satisfies the givenpredicate, dropping all preceding elements.- Parameters:
predicate- a condition tested on each element- Returns:
- a new instance starting from the first element matching the predicate
- Throws:
NullPointerException- ifpredicateis null
-
dropWhile
Returns a newTraversablestarting from the first element that does not satisfy the givenpredicate, dropping all preceding elements.This is equivalent to
dropUntil(predicate.negate()), which is useful for method references that cannot be negated directly.- Parameters:
predicate- a condition tested on each element- Returns:
- a new instance starting from the first element not matching the predicate
- Throws:
NullPointerException- ifpredicateis null
-
equals
Determines whether this collection is equal to the given object.In Vavr, there are four basic collection types:
Seq– sequential elementsSet– distinct elementsMap– key-value pairsMultimap– keys mapped to multiple values
- They are of the same collection type (Seq, Set, Map, Multimap)
- They contain the same elements
- For
Seq, the element order is the same
For
MapandMultimap, two entries(key1, value1)and(key2, value2)are equal if both their keys and values are equal.Additional notes:
- No collection equals
null(e.g.,Queue(1) != null) - Null elements are allowed and treated as expected
(e.g.,
List(null, 1) == Stream(null, 1),HashMap((null,1)) == LinkedHashMap((null,1))) - Element order matters only for
Seq - Other collection classes are equal if their types and elements (in iteration order) are equal
- Iterators are compared by reference only
-
existsUnique
Checks whether there is exactly one element in this traversable for which the given predicate holds.- Parameters:
predicate- the condition to test elements- Returns:
trueif exactly one element satisfies the predicate,falseotherwise- Throws:
NullPointerException- ifpredicateisnull
-
filter
Returns a new traversable containing only the elements that satisfy the given predicate.- Parameters:
predicate- the condition to test elements- Returns:
- a traversable with elements matching the predicate
- Throws:
NullPointerException- ifpredicateis null
-
reject
Returns a new traversable containing only the elements that do not satisfy the given predicate.This is equivalent to
filter(predicate.negate()).- Parameters:
predicate- the condition to test elements- Returns:
- a traversable with elements not matching the predicate
- Throws:
NullPointerException- ifpredicateis null
-
find
Returns the first element that satisfies the given predicate.- Parameters:
predicate- the condition to test elements- Returns:
Some(element)if a matching element is found, otherwiseNone; the element may benull- Throws:
NullPointerException- ifpredicateis null
-
findLast
Returns the last element that satisfies the given predicate.Equivalent to
reverse().find(predicate)but potentially more efficient.- Parameters:
predicate- the condition to test elements- Returns:
Some(element)if a matching element is found, otherwiseNone; the element may benull- Throws:
NullPointerException- ifpredicateis null
-
flatMap
Transforms each element of this Traversable into anIterableof elements and flattens the resulting iterables into a single Traversable.- Type Parameters:
U- the type of elements in the resulting Traversable- Parameters:
mapper- a function mapping elements to iterables- Returns:
- a new Traversable containing all elements produced by applying
mapperand flattening - Throws:
NullPointerException- ifmapperis null
-
foldLeft
Description copied from interface:FoldableFolds the elements of this structure from the left, starting with the givenzerovalue and successively applying thecombinefunction to each element.Folding from the left means that elements are combined in the order they are encountered, associating each step with the accumulated result so far.
Example:
// Result: "cba!" List.of("a", "b", "c").foldLeft("!", (acc, x) -> x + acc); -
foldRight
Description copied from interface:FoldableFolds the elements of this structure from the right, starting with the givenzerovalue and successively applying thecombinefunction to each element.Folding from the right means that elements are combined starting from the last element and associating each step with the accumulated result so far.
Example:
// Result: "!cba" List.of("a", "b", "c").foldRight("!", (x, acc) -> acc + x); -
forEachWithIndex
Performs the given action on each element of this Traversable along with its index.This method is more efficient than
iterator().zipWithIndex().forEach()because it avoids creating intermediateTuple2objects and boxing integers.Note that the iteration order may vary between calls depending on the underlying Traversable implementation. Also, if this Traversable is lazily evaluated (e.g., a
Stream), the method may loop indefinitely.- Parameters:
action- an action to perform on each element and its index- Throws:
NullPointerException- ifactionis null
-
get
Returns the first element of thisTraversablein iteration order.- Specified by:
getin interfaceValue<T>- Returns:
- the first element
- Throws:
NoSuchElementException- if thisTraversableis empty
-
groupBy
Groups elements of thisTraversablebased on a classifier function.- Type Parameters:
C- The type of the group keys- Parameters:
classifier- A function that assigns each element to a group- Returns:
- A map where each key corresponds to a group of elements
- Throws:
NullPointerException- ifclassifieris null- See Also:
-
grouped
Splits thisTraversableinto consecutive blocks of the given size.Let
lengthbe the number of elements in thisTraversable:- If empty, the resulting
Iteratoris empty. - If
size <= length, the resultingIteratorcontainslength / sizeblocks of sizesizeand possibly a final smaller block of sizelength % size. - If
size > length, the resultingIteratorcontains a single block of sizelength.
Examples:
[].grouped(1) = [] [].grouped(0) throws [].grouped(-1) throws [1,2,3,4].grouped(2) = [[1,2],[3,4]] [1,2,3,4,5].grouped(2) = [[1,2],[3,4],[5]] [1,2,3,4].grouped(5) = [[1,2,3,4]]Note:
grouped(size)is equivalent tosliding(size, size).- Parameters:
size- the block size; must be positive- Returns:
- an
Iteratorover blocks of elements - Throws:
IllegalArgumentException- ifsizeis zero or negative
- If empty, the resulting
-
hasDefiniteSize
boolean hasDefiniteSize()Indicates whether thisTraversablehas a known finite size.This should typically be implemented by concrete classes, not interfaces.
- Returns:
trueif the number of elements is finite and known,falseotherwise.
-
head
T head()Returns the first element of this non-emptyTraversable.- Returns:
- the first element
- Throws:
NoSuchElementException- if thisTraversableis empty
-
headOption
Returns the first element of thisTraversableas anOption.- Returns:
Some(element)if non-empty, otherwiseNone
-
hashCode
int hashCode()Returns the hash code of this collection.Vavr distinguishes between collections with predictable iteration order (like
Seq) and collections with arbitrary iteration order (likeSet,Map, andMultimap). In all cases, the hash of an empty collection is defined as1.For collections with predictable iteration order, the hash is computed as:
int hash = 1; for (T t : this) { hash = hash * 31 + Objects.hashCode(t); }For collections with arbitrary iteration order, the hash is computed to be independent of element order:
int hash = 1; for (T t : this) { hash += Objects.hashCode(t); }Note that these algorithms may change in future Vavr versions. Hash codes are generally not cached, unlike size/length, because caching would increase memory usage due to persistent tree-based structures. Computing the hash code is linear in time, O(n). For frequently re-used collections (e.g., as
HashMapkeys), caching can be done externally using a wrapper, for example:public final class Hashed<K> { private final K key; private final Lazy<Integer> hashCode; public Hashed(K key) { this.key = key; this.hashCode = Lazy.of(() -> Objects.hashCode(key)); } public K key() { return key; } @Override public boolean equals(Object o) { if (o == key) return true; if (key != null && o instanceof Hashed) return key.equals(((Hashed<?>) o).key); return false; } @Override public int hashCode() { return hashCode.get(); } @Override public String toString() { return "Hashed(" + key + ")"; } } -
init
Traversable<T> init()Returns all elements of this Traversable except the last one.This is the dual of
tail().- Returns:
- a new instance containing all elements except the last
- Throws:
UnsupportedOperationException- if this Traversable is empty
-
initOption
Returns all elements of this Traversable except the last one, wrapped in anOption.This is the dual of
tailOption().- Returns:
Some(traversable)if non-empty, orNoneif this Traversable is empty
-
isDistinct
default boolean isDistinct()Indicates whether this Traversable may contain only distinct elements.- Returns:
trueif this Traversable may contain only distinct elements,falseotherwise
-
isEmpty
default boolean isEmpty()Checks if this Traversable contains no elements. -
isOrdered
default boolean isOrdered()Indicates whether this Traversable is ordered according to its natural or specified order.- Returns:
trueif this Traversable is ordered,falseotherwise
-
isSequential
default boolean isSequential()Indicates whether the elements of this Traversable appear in encounter (insertion) order.- Returns:
trueif insertion order is preserved,falseotherwise
-
isSingleValued
default boolean isSingleValued()Indicates that this Traversable may contain multiple elements.- Specified by:
isSingleValuedin interfaceValue<T>- Returns:
falsesince Traversable is multi-valued by design
-
isTraversableAgain
boolean isTraversableAgain()Checks if this Traversable can be traversed multiple times without side effects.Implementations should provide the correct behavior; this is not meant for interfaces alone.
- Returns:
trueif this Traversable is guaranteed to be repeatably traversable,falseotherwise
-
iterator
-
last
T last()Returns the last element of this Traversable.- Returns:
- the last element
- Throws:
NoSuchElementException- if this Traversable is empty
-
lastOption
Returns the last element of this Traversable as anOption.- Returns:
Some(element)if not empty, otherwiseNone
-
length
int length()Returns the number of elements in this Traversable.Equivalent to
size().- Returns:
- the number of elements
-
map
Transforms the elements of this Traversable to a new type, preserving order if defined.- Specified by:
mapin interfaceValue<T>- Type Parameters:
U- the target element type- Parameters:
mapper- a mapping function- Returns:
- a new Traversable containing the mapped elements
- Throws:
NullPointerException- ifmapperis null
-
mapTo
Description copied from interface:ValueMaps the underlying value to another fixed value. -
mapToVoid
Description copied from interface:ValueMaps the underlying value to Void -
max
Returns the maximum element of this Traversable according to the natural order of its elements.Note that the underlying order of sorted collections is not considered—only the natural ordering of elements matters.
Examples:
List.empty().max() // = None List.of(1, 2, 3).max() // = Some(3) List.of("a", "b", "c").max() // = Some("c") List.of(1.0, Double.NaN).max() // = NaN List.of(1, "a").max() // throws ClassCastException- Returns:
Some(maximum)if this Traversable is not empty, otherwiseNone- Throws:
NullPointerException- if any element is nullClassCastException- if elements do not implementComparable
-
maxBy
Returns the maximum element of this Traversable according to the given comparator.If the Traversable is empty,
Noneis returned.- Parameters:
comparator- a non-nullComparatorto determine element ordering- Returns:
Some(maximum)if this Traversable is not empty, otherwiseNone- Throws:
NullPointerException- ifcomparatoris null
-
maxBy
default <U extends Comparable<? super U>> Option<T> maxBy(@NonNull Function<? super T, ? extends U> f) Returns the element of this Traversable whose mapped value, according to the given function, is maximal.The mapping function
ftransforms elements of typeTto a comparable typeU, and the element with the largestUvalue is returned.- Type Parameters:
U- the type used for comparison, must implementComparable- Parameters:
f- a non-null function mapping elements to a comparable type- Returns:
Some(element)whose mapped value is maximal, orNoneif this Traversable is empty- Throws:
NullPointerException- iffis null
-
min
Returns the minimum element of this Traversable according to its natural order in O(n).The underlying order of sorted collections is not considered. For numeric types
DoubleandFloat, if any element isNaN, the result isNaNinstead of following the natural order.Examples:
List.empty().min() // = None List.of(1, 2, 3).min() // = Some(1) List.of("a", "b", "c").min() // = Some("a") List.of(1.0, Double.NaN).min() // = NaN List.of(1, "a").min() // throws- Returns:
Some(minimum)of this elements, orNoneif this Traversable is empty- Throws:
NullPointerException- if an element is nullClassCastException- if the elements do not have a natural order, i.e., do not implementComparable
-
minBy
Returns the minimum element of this Traversable according to a given comparator.- Parameters:
comparator- a non-null comparator used to determine ordering- Returns:
Some(minimum)of this elements, orNoneif this Traversable is empty- Throws:
NullPointerException- ifcomparatoris null
-
minBy
default <U extends Comparable<? super U>> Option<T> minBy(@NonNull Function<? super T, ? extends U> f) Returns the element of this Traversable whose mapped value is minimal according to natural order.- Type Parameters:
U- the type of the comparable value- Parameters:
f- a function mapping elements to a comparable value- Returns:
- the element of type T whose mapped value is minimal, wrapped in
Some, orNoneif empty - Throws:
NullPointerException- iffis null
-
mkCharSeq
Concatenates the string representations of all elements in this Traversable.Equivalent to
mkCharSeq("", "", "").- Returns:
- a new
CharSeqcontaining all elements concatenated
-
mkCharSeq
Concatenates the string representations of all elements in this Traversable, separated by a delimiter.Equivalent to
mkCharSeq("", delimiter, "").- Parameters:
delimiter- a string placed between elements- Returns:
- a new
CharSeqwith elements separated by the delimiter
-
mkCharSeq
Concatenates the string representations of all elements in this Traversable with a prefix, delimiter, and suffix.Example:
List.of("a", "b", "c").mkCharSeq("Chars(", ", ", ")") = CharSeq.of("Chars(a, b, c)")- Parameters:
prefix- a string prepended to the resultdelimiter- a string placed between elementssuffix- a string appended to the result- Returns:
- a new
CharSeqcontaining the formatted concatenation of elements
-
mkString
Concatenates the string representations of all elements in this Traversable.Equivalent to
mkString("", "", "").- Returns:
- a new
Stringcontaining all elements concatenated
-
mkString
Concatenates the string representations of all elements in this Traversable, separated by a delimiter.Equivalent to
mkString("", delimiter, "").- Parameters:
delimiter- a string placed between elements- Returns:
- a new
Stringcontaining the concatenated elements
-
mkString
Concatenates the string representations of all elements in this Traversable with a prefix, delimiter, and suffix.Example:
List.of("a", "b", "c").mkString("Chars(", ", ", ")") = "Chars(a, b, c)"- Parameters:
prefix- a string prepended to the resultdelimiter- a string placed between elementssuffix- a string appended to the result- Returns:
- a new
Stringcontaining the formatted concatenation of elements
-
nonEmpty
default boolean nonEmpty()Checks if thisTraversablecontains at least one element.Equivalent to
!isEmpty().- Returns:
trueif this Traversable is not empty,falseotherwise
-
orElse
Returns thisTraversableif it is non-empty; otherwise, returns the given alternative.- Parameters:
other- an alternativeTraversableto return if this is empty- Returns:
- this
Traversableif non-empty, otherwiseother
-
orElse
Returns thisTraversableif it is non-empty; otherwise, returns the result of evaluating the given supplier.- Parameters:
supplier- a supplier of an alternativeTraversableif this is empty- Returns:
- this
Traversableif non-empty, otherwise the result ofsupplier.get() - Throws:
NullPointerException- ifsupplieris null
-
partition
Tuple2<? extends Traversable<T>,? extends Traversable<T>> partition(@NonNull Predicate<? super T> predicate) Splits thisTraversableinto two partitions according to a predicate.The first partition contains all elements that satisfy the predicate, and the second contains all elements that do not. The original iteration order is preserved.
- Parameters:
predicate- a predicate used to classify elements- Returns:
- a
Tuple2containing the two resultingTraversableinstances - Throws:
NullPointerException- ifpredicateis null
-
peek
Description copied from interface:ValuePerforms the givenactionon the first element if this is an eager implementation. Performs the givenactionon all elements (the first immediately, successive deferred), if this is a lazy implementation. -
product
Calculates the product of the elements in thisTraversable.Supported element types are
Byte,Double,Float,Integer,Long,Short,BigInteger, andBigDecimal.Examples:
List.empty().product() // = 1 List.of(1, 2, 3).product() // = 6L List.of(0.1, 0.2, 0.3).product() // = 0.006 List.of("apple", "pear").product() // throwsFor type-safe multiplication of elements, consider using
Foldable.fold(Object, BiFunction).- Returns:
- a
Numberrepresenting the product of the elements - Throws:
UnsupportedOperationException- if the elements are not numeric
-
reduceLeft
Reduces the elements of this Traversable from the left using the given binary operation.- Specified by:
reduceLeftin interfaceFoldable<T>- Parameters:
op- A binary operation combining two elements of type T- Returns:
- the result of the reduction
- Throws:
NoSuchElementException- if this Traversable is emptyNullPointerException- ifopis null
-
reduceLeftOption
Reduces the elements of this Traversable from the left using the given binary operation, returning the result wrapped in anOption.- Specified by:
reduceLeftOptionin interfaceFoldable<T>- Parameters:
op- A binary operation combining two elements of type T- Returns:
Some(reduced value)orNoneif this Traversable is empty- Throws:
NullPointerException- ifopis null
-
reduceRight
Reduces the elements of this Traversable from the right using the given binary operation.- Specified by:
reduceRightin interfaceFoldable<T>- Parameters:
op- A binary operation combining two elements of type T- Returns:
- the result of the reduction
- Throws:
NoSuchElementException- if this Traversable is emptyNullPointerException- ifopis null
-
reduceRightOption
Reduces the elements of this Traversable from the right using the given binary operation, returning the result wrapped in anOption.- Specified by:
reduceRightOptionin interfaceFoldable<T>- Parameters:
op- A binary operation combining two elements of type T- Returns:
Some(reduced value)orNoneif this Traversable is empty- Throws:
NullPointerException- ifopis null
-
replace
Replaces the first occurrence ofcurrentElementwithnewElement, if it exists.- Parameters:
currentElement- the element to be replacednewElement- the replacement element- Returns:
- a new Traversable with the first occurrence of
currentElementreplaced bynewElement
-
replaceAll
Replaces all occurrences ofcurrentElementwithnewElement.- Parameters:
currentElement- the element to be replacednewElement- the replacement element- Returns:
- a new Traversable with all occurrences of
currentElementreplaced bynewElement
-
retainAll
Retains only the elements from this Traversable that are contained in the givenelements.- Parameters:
elements- the elements to keep- Returns:
- a new Traversable containing only the elements present in
elements, in their original order - Throws:
NullPointerException- ifelementsis null
-
scan
Computes a prefix scan of the elements of this Traversable.The neutral element
zeromay be applied more than once.- Parameters:
zero- the neutral element for the operatoroperation- an associative binary operator- Returns:
- a new Traversable containing the prefix scan of the elements
- Throws:
NullPointerException- ifoperationis null
-
scanLeft
Produces a collection containing cumulative results of applying the operator from left to right.Will not terminate for infinite collections. The results may vary across runs unless the collection is ordered.
- Type Parameters:
U- the type of the resulting elements- Parameters:
zero- the initial valueoperation- a binary operator applied to the intermediate result and each element- Returns:
- a new Traversable containing the cumulative results
- Throws:
NullPointerException- ifoperationis null
-
scanRight
<U> Traversable<U> scanRight(U zero, @NonNull BiFunction<? super T, ? super U, ? extends U> operation) Produces a collection containing cumulative results of applying the operator from right to left.The head of the resulting collection is the last cumulative result. Will not terminate for infinite collections. Results may vary across runs unless the collection is ordered.
- Type Parameters:
U- the type of the resulting elements- Parameters:
zero- the initial valueoperation- a binary operator applied to each element and the intermediate result- Returns:
- a new Traversable containing the cumulative results
- Throws:
NullPointerException- ifoperationis null
-
single
Returns the single element of this Traversable.- Returns:
- the single element
- Throws:
NoSuchElementException- if the Traversable is empty or contains more than one element
-
singleOption
Returns the single element of this Traversable as anOption.- Returns:
Some(element)if the Traversable contains exactly one element, orNoneotherwise.
-
size
default int size()Returns the number of elements in this Traversable.Alias for
length().- Returns:
- the number of elements
-
slideBy
Partitions thisTraversableinto consecutive non-overlapping windows according to a classification function.Each window contains elements with the same class, as determined by
classifier. Two consecutive elements belong to the same window only ifclassifierreturns equal values for both. Otherwise, the current window ends and a new window begins with the next element.Examples:
[].slideBy(Function.identity()) = [] [1,2,3,4,4,5].slideBy(Function.identity()) = [[1],[2],[3],[4,4],[5]] [1,2,3,10,12,5,7,20,29].slideBy(x -> x / 10) = [[1,2,3],[10,12],[5,7],[20,29]]- Parameters:
classifier- A function classifying elements into groups- Returns:
- An
Iteratorof windows (grouped elements) - Throws:
NullPointerException- ifclassifieris null
-
sliding
Slides a window of a givensizeover thisTraversablewith a step size of 1.This is equivalent to calling
sliding(int, int)with a step size of 1.- Parameters:
size- a positive window size- Returns:
- An
Iteratorof windows, each containing up tosizeelements - Throws:
IllegalArgumentException- ifsizeis zero or negative
-
sliding
Slides a window of a specificsizewith a givenstepover thisTraversable.Examples:
[].sliding(1, 1) = [] [1,2,3,4,5].sliding(2, 3) = [[1,2],[4,5]] [1,2,3,4,5].sliding(2, 4) = [[1,2],[5]] [1,2,3,4,5].sliding(2, 5) = [[1,2]] [1,2,3,4].sliding(5, 3) = [[1,2,3,4],[4]]- Parameters:
size- a positive window sizestep- a positive step size- Returns:
- an
Iteratorof windows with the given size and step - Throws:
IllegalArgumentException- ifsizeorstepare zero or negative
-
span
Tuple2<? extends Traversable<T>,? extends Traversable<T>> span(@NonNull Predicate<? super T> predicate) Splits thisTraversableinto a prefix and remainder according to the givenpredicate.The first element of the returned
Tupleis the longest prefix of elements satisfyingpredicate, and the second element is the remaining elements.- Parameters:
predicate- a predicate used to determine the prefix- Returns:
- a
Tuplecontaining the prefix and remainder - Throws:
NullPointerException- ifpredicateis null
-
spliterator
- Specified by:
spliteratorin interfaceIterable<T>- Specified by:
spliteratorin interfaceValue<T>
-
sum
Calculates the sum of the elements in thisTraversable. Supported numeric types areByte,Double,Float,Integer,Long,Short,BigInteger, andBigDecimal.Examples:
List.empty().sum() // = 0 List.of(1, 2, 3).sum() // = 6L List.of(0.1, 0.2, 0.3).sum() // = 0.6 List.of("apple", "pear").sum() // throwsSee also
Foldable.fold(Object, BiFunction)for type-safe summation of elements.- Returns:
- a
Numberrepresenting the sum of the elements - Throws:
UnsupportedOperationException- if elements are not numeric
-
tail
Traversable<T> tail()Returns a newTraversablewithout its first element.- Returns:
- a new
Traversablecontaining all elements except the first - Throws:
UnsupportedOperationException- if thisTraversableis empty
-
tailOption
Returns a newTraversablewithout its first element as anOption.- Returns:
Some(traversable)if non-empty, otherwiseNone
-
take
Returns the firstnelements of thisTraversable, or all elements ifnexceeds the length.Equivalent to
sublist(0, max(0, min(length(), n))), but safe forn < 0orn > length().If
n < 0, an empty instance is returned. Ifn > length(), the full instance is returned.- Parameters:
n- the number of elements to take- Returns:
- a new
Traversablecontaining the firstnelements
-
takeRight
Returns the lastnelements of thisTraversable, or all elements ifnexceeds the length.Equivalent to
sublist(max(0, length() - n), length()), but safe forn < 0orn > length().If
n < 0, an empty instance is returned. Ifn > length(), the full instance is returned.- Parameters:
n- the number of elements to take from the end- Returns:
- a new
Traversablecontaining the lastnelements
-
takeUntil
Takes elements from thisTraversableuntil the given predicate holds for an element.Equivalent to
takeWhile(predicate.negate()), but useful when using method references that cannot be negated directly.- Parameters:
predicate- a condition tested sequentially on the elements- Returns:
- a new
Traversablecontaining all elements before the first one that satisfies the predicate - Throws:
NullPointerException- ifpredicateis null
-
takeWhile
Takes elements from thisTraversablewhile the given predicate holds.- Parameters:
predicate- a condition tested sequentially on the elements- Returns:
- a new
Traversablecontaining all elements up to (but not including) the first one that does not satisfy the predicate - Throws:
NullPointerException- ifpredicateis null
-
unzip
<T1,T2> Tuple2<? extends Traversable<T1>,? extends Traversable<T2>> unzip(@NonNull Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper) Unzips the elements of thisTraversableby mapping each element to a pair and splitting them into two separateTraversablecollections.- Type Parameters:
T1- type of the first element in the resulting pairsT2- type of the second element in the resulting pairs- Parameters:
unzipper- a function that maps elements of thisTraversableto pairs- Returns:
- a
Tuple2containing twoTraversablecollections with the split elements - Throws:
NullPointerException- ifunzipperis null
-
unzip3
<T1,T2, Tuple3<? extends Traversable<T1>,T3> ? extends Traversable<T2>, unzip3? extends Traversable<T3>> (@NonNull Function<? super T, Tuple3<? extends T1, ? extends T2, ? extends T3>> unzipper) Unzips the elements of thisTraversableby mapping each element to a triple and splitting them into three separateTraversablecollections.- Type Parameters:
T1- type of the first element in the resulting triplesT2- type of the second element in the resulting triplesT3- type of the third element in the resulting triples- Parameters:
unzipper- a function that maps elements of thisTraversableto triples- Returns:
- a
Tuple3containing threeTraversablecollections with the split elements - Throws:
NullPointerException- ifunzipperis null
-
zip
Returns aTraversableformed by pairing elements of thisTraversablewith elements of anotherIterable. Pairing stops when either collection runs out of elements; any remaining elements in the longer collection are ignored.The length of the resulting
Traversableis the minimum of the lengths of thisTraversableandthat.- Type Parameters:
U- the type of elements in the second half of each pair- Parameters:
that- anIterableproviding the second element of each pair- Returns:
- a new
Traversablecontaining pairs of corresponding elements - Throws:
NullPointerException- ifthatis null
-
zipAll
Returns aTraversableformed by pairing elements of thisTraversablewith elements of anotherIterable, filling in placeholder elements when one collection is shorter than the other.The length of the resulting
Traversableis the maximum of the lengths of thisTraversableandthat.If this
Traversableis shorter thanthat,thisElemis used as a filler. Conversely, ifthatis shorter,thatElemis used.- Type Parameters:
U- the type of elements in the second half of each pair- Parameters:
that- anIterableproviding the second element of each pairthisElem- the element used to fill missing values if thisTraversableis shorter thanthatthatElem- the element used to fill missing values ifthatis shorter than thisTraversable- Returns:
- a new
Traversablecontaining pairs of elements, including fillers as needed - Throws:
NullPointerException- ifthatis null
-
zipWith
<U,R> Traversable<R> zipWith(@NonNull Iterable<? extends U> that, BiFunction<? super T, ? super U, ? extends R> mapper) Returns aTraversableby combining elements of thisTraversablewith elements of anotherIterableusing a mapping function. Pairing stops when either collection runs out of elements.The length of the resulting
Traversableis the minimum of the lengths of thisTraversableandthat.- Type Parameters:
U- the type of elements in the second parameter of the mapperR- the type of elements in the resultingTraversable- Parameters:
that- anIterableproviding the second parameter of the mappermapper- a function that combines elements from this andthatinto a new element- Returns:
- a new
Traversablecontaining mapped elements - Throws:
NullPointerException- ifthatormapperis null
-
zipWithIndex
Traversable<Tuple2<T,Integer>> zipWithIndex()Zips thisTraversablewith its indices, starting at 0.- Returns:
- a new
Traversablecontaining each element paired with its index
-
zipWithIndex
Zips thisTraversablewith its indices and maps the resulting pairs using the provided mapper.- Type Parameters:
U- the type of elements in the resultingTraversable- Parameters:
mapper- a function mapping an element and its index to a new element- Returns:
- a new
Traversablecontaining the mapped elements - Throws:
NullPointerException- ifmapperis null
-