Interface Traversable<T>
- Type Parameters:
T- Component type
- 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:
AbstractIterator, AbstractMultimap, AbstractQueue, Array, BitSetModule.AbstractBitSet, BitSetModule.BitSet1, BitSetModule.BitSet2, BitSetModule.BitSetIterator, BitSetModule.BitSetN, CharSeq, HashArrayMappedTrieModule.LeafNodeIterator, HashMap, HashMultimap, HashSet, IteratorModule.CachedIterator, IteratorModule.ConcatIterator, IteratorModule.DistinctIterator, IteratorModule.EmptyIterator, IteratorModule.GroupedIterator, LinkedHashMap, LinkedHashMultimap, LinkedHashSet, List.Cons, List.Nil, PriorityQueue, Queue, Stream.Cons, Stream.Empty, StreamModule.AppendElements, StreamModule.ConsImpl, StreamModule.FlatMapIterator, StreamModule.StreamIterator, Tree.Empty, Tree.Node, TreeMap, TreeMultimap, TreeSet, Vector
Iterable.iterator(), which may vary each time it is called.
Basic operations:
collect(PartialFunction)Value.contains(Object)containsAll(Iterable)head()headOption()init()initOption()isEmpty()last()lastOption()length()size()tail()tailOption()
forEachWithIndex(ObjIntConsumer)grouped(int)iterator()slideBy(Function)sliding(int)sliding(int, int)
average()max()maxBy(Comparator)maxBy(Function)min()minBy(Comparator)minBy(Function)product()sum()
count(Predicate)Foldable.fold(Object, BiFunction)foldLeft(Object, BiFunction)foldRight(Object, BiFunction)mkString()mkString(CharSequence)mkString(CharSequence, CharSequence, CharSequence)Foldable.reduce(BiFunction)Foldable.reduceOption(BiFunction)reduceLeft(BiFunction)reduceLeftOption(BiFunction)reduceRight(BiFunction)reduceRightOption(BiFunction)
drop(int)dropRight(int)dropUntil(Predicate)dropWhile(Predicate)filter(Predicate)reject(Predicate)find(Predicate)findLast(Predicate)groupBy(Function)partition(Predicate)retainAll(Iterable)take(int)takeRight(int)takeUntil(Predicate)takeWhile(Predicate)
existsUnique(Predicate)hasDefiniteSize()isDistinct()isOrdered()isSequential()isTraversableAgain()
distinct()distinctBy(Comparator)distinctBy(Function)flatMap(Function)map(Function)replace(Object, Object)replaceAll(Object, Object)scan(Object, BiFunction)scanLeft(Object, BiFunction)scanRight(Object, BiFunction)span(Predicate)unzip(Function)unzip3(Function)zip(Iterable)zipAll(Iterable, Object, Object)zipWithIndex()
-
Method Summary
Modifier and TypeMethodDescriptionMatches each element with a unique key that you extract from it.average()Calculates the average of this elements, assuming that the element type isNumber.<R> Traversable<R> collect(PartialFunction<? super T, ? extends R> partialFunction) Collects all elements that are in the domain of the givenpartialFunctionby mapping the elements to typeR.default booleancontainsAll(Iterable<? extends T> elements) Tests if this Traversable contains all given elements.default intCounts the elements which satisfy the given predicate.distinct()Returns a new version of this which contains no duplicates.distinctBy(Comparator<? super T> comparator) Returns a new version of this which contains no duplicates.<U> Traversable<T> distinctBy(Function<? super T, ? extends U> keyExtractor) Returns a new version of this which contains no duplicates.drop(int n) Drops the first n elements of this or all elements, if this length < n.dropRight(int n) Drops the last n elements of this or all elements, if this length < n.Drops elements until the predicate holds for the current element.Drops elements while the predicate holds for the current element.booleanIn Vavr there are four basic classes of collections: Seq (sequential elements) Set (distinct elements) Map (indexed elements) Multimap (indexed collections) Two collection instances of these classes are equal if and only if both collections belong to the same basic collection class (Seq, Set, Map or Multimap) contain the same elements have the same element order, if the collections are of type Seq Two Map/Multimap elements, resp.default booleanexistsUnique(Predicate<? super T> predicate) Checks, if a unique elements exists such that the predicate holds.Returns a new traversable consisting of all elements which satisfy the given predicate.Returns the first element of this which satisfies the given predicate.Returns the last element of this which satisfies the given predicate.<U> Traversable<U> FlatMaps this Traversable.default <U> UfoldLeft(U zero, BiFunction<? super U, ? super T, ? extends U> f) Folds this elements from the left, starting withzeroand successively callingcombine.<U> UfoldRight(U zero, BiFunction<? super T, ? super U, ? extends U> f) Folds this elements from the right, starting withzeroand successively callingcombine.default voidforEachWithIndex(ObjIntConsumer<? super T> action) Performs an action on each element.default Tget()Gets the first value in iteration order if thisTraversableis not empty, otherwise throws.<C> Map<C, ? extends Traversable<T>> Groups this elements by classifying the elements.Iterator<? extends Traversable<T>> grouped(int size) Groups thisTraversableinto fixed size blocks.booleanChecks if this Traversable is known to have a finite size.inthashCode()Returns the hash code of this collection.head()Returns the first element of a non-empty Traversable.Returns the first element of a non-empty Traversable asOption.init()Dual of tail(), returning all elements except the last.default Option<? extends Traversable<T>> Dual of tailOption(), returning all elements except the last asOption.default booleanChecks if this Traversable may consist of distinct elements only.default booleanisEmpty()Checks if this Traversable is empty.default booleanChecks if this Traversable is ordereddefault booleanChecks if the elements of this Traversable appear in encounter order.default booleanEach of Vavr's collections may contain more than one element.booleanChecks if this Traversable can be repeatedly traversed.iterator()An iterator by means of head() and tail().last()Dual of head(), returning the last element.Dual of headOption(), returning the last element asOption.intlength()Computes the number of elements of this Traversable.<U> Traversable<U> Maps the elements of thisTraversableto elements of a new type preserving their order, if any.max()Calculates the maximum of this elements according to their natural order.maxBy(Comparator<? super T> comparator) Calculates the maximum of this elements using a specific comparator.default <U extends Comparable<? super U>>
Option<T> Calculates the maximum of this elements within the co-domain of a specific function.min()Calculates the minimum of this elements according to their natural order in O(n).minBy(Comparator<? super T> comparator) Calculates the minimum of this elements using a specific comparator.default <U extends Comparable<? super U>>
Option<T> Calculates the minimum of this elements within the co-domain of a specific function.default CharSeqJoins the elements of this by concatenating their string representations.default CharSeqmkCharSeq(CharSequence delimiter) Joins the string representations of this elements using a specific delimiter.default CharSeqmkCharSeq(CharSequence prefix, CharSequence delimiter, CharSequence suffix) Joins the string representations of this elements using a specific delimiter, prefix and suffix.default StringmkString()Joins the elements of this by concatenating their string representations.default StringmkString(CharSequence delimiter) Joins the string representations of this elements using a specific delimiter.default StringmkString(CharSequence prefix, CharSequence delimiter, CharSequence suffix) Joins the string representations of this elements using a specific delimiter, prefix and suffix.static <T> Traversable<T> narrow(Traversable<? extends T> traversable) Narrows a widenedTraversable<? extends T>toTraversable<T>by performing a type-safe cast.default booleannonEmpty()Checks, thisTraversableis not empty.Returns thisTraversableif it is nonempty, otherwise return the alternative.Returns thisTraversableif it is nonempty, otherwise return the result of evaluating supplier.Tuple2<? extends Traversable<T>, ? extends Traversable<T>> Creates a partition of thisTraversableby splitting this elements in two in distinct traversables according to a predicate.Performs the givenactionon the first element if this is an eager implementation.default Numberproduct()Calculates the product of this elements.default TreduceLeft(BiFunction<? super T, ? super T, ? extends T> op) Accumulates the elements of this Traversable by successively calling the given operationopfrom the left.reduceLeftOption(BiFunction<? super T, ? super T, ? extends T> op) Shortcut forisEmpty() ? Option.none() : Option.some(reduceLeft(op)).default TreduceRight(BiFunction<? super T, ? super T, ? extends T> op) Accumulates the elements of this Traversable by successively calling the given operationopfrom the right.reduceRightOption(BiFunction<? super T, ? super T, ? extends T> op) Shortcut forisEmpty() ? Option.none() : Option.some(reduceRight(op)).default Traversable<T> Returns a new traversable consisting of all elements which do not satisfy the given predicate.Replaces the first occurrence (if exists) of the given currentElement with newElement.replaceAll(T currentElement, T newElement) Replaces all occurrences of the given currentElement with newElement.Keeps all occurrences of the given elements from this.Computes a prefix scan of the elements of the collection.<U> Traversable<U> scanLeft(U zero, BiFunction<? super U, ? super T, ? extends U> operation) Produces a collection containing cumulative results of applying the operator going left to right.<U> Traversable<U> scanRight(U zero, BiFunction<? super T, ? super U, ? extends U> operation) Produces a collection containing cumulative results of applying the operator going right to left.default Tsingle()Returns the single element of this Traversable or throws, if this is empty or contains more than one element.Returns the only element of a Traversable asOption.default intsize()Computes the number of elements of this Traversable.Iterator<? extends Traversable<T>> Slides a non-overlapping window of a variable size over thisTraversable.Iterator<? extends Traversable<T>> sliding(int size) Slides a window of a specificsizeand step size 1 over thisTraversableby callingsliding(int, int).Iterator<? extends Traversable<T>> sliding(int size, int step) Slides a window of a specificsizeandstepsize over thisTraversable.Tuple2<? extends Traversable<T>, ? extends Traversable<T>> Returns a tuple where the first element is the longest prefix of elements that satisfy the givenpredicateand the second element is the remainder.default Spliterator<T> default Numbersum()Calculates the sum of this elements.tail()Drops the first element of a non-empty Traversable.Option<? extends Traversable<T>> Drops the first element of a non-empty Traversable and returns anOption.take(int n) Takes the first n elements of this or all elements, if this length < n.takeRight(int n) Takes the last n elements of this or all elements, if this length < n.Takes elements until the predicate holds for the current element.Takes elements while the predicate holds for the current element.<T1,T2> Tuple2 <? extends Traversable<T1>, ? extends Traversable<T2>> Unzips this elements by mapping this elements to pairs which are subsequently split into two distinct sets.<T1,T2, T3> Tuple3 <? extends Traversable<T1>, ? extends Traversable<T2>, ? extends Traversable<T3>> Unzips this elements by mapping this elements to triples which are subsequently split into three distinct sets.<U> Traversable<Tuple2<T, U>> Returns a traversable formed from this traversable and another Iterable collection by combining corresponding elements in pairs.<U> Traversable<Tuple2<T, U>> Returns a traversable formed from this traversable and another Iterable by combining corresponding elements in pairs.<U,R> Traversable <R> zipWith(Iterable<? extends U> that, BiFunction<? super T, ? super U, ? extends R> mapper) Returns a traversable formed from this traversable and another Iterable collection by mapping elements.Zips this traversable with its indices.<U> Traversable<U> zipWithIndex(BiFunction<? super T, ? super Integer, ? extends U> mapper) Zips this traversable with its indices by applying mapper provided.Methods inherited from interface Foldable
fold, reduce, reduceOptionMethods inherited from interface 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 a widenedTraversable<? extends T>toTraversable<T>by performing a type-safe cast. This is eligible because immutable/read-only collections are covariant.- Type Parameters:
T- Component type of theTraversable.- Parameters:
traversable- AnTraversable.- Returns:
- the given
traversableinstance as narrowed typeTraversable<T>.
-
arrangeBy
Matches each element with a unique key that you extract from it. If the same key is present twice, the function will returnNone.- Type Parameters:
K- key class type- Parameters:
getKey- A function which extracts a key from elements- Returns:
- A Map containing the elements arranged by their keys.
- Throws:
NullPointerException- ifgetKeyis null.- See Also:
-
average
Calculates the average of this elements, assuming that the element type isNumber. Since we do not know if the component typeTis of typeNumber, theaverage()call might throw at runtime (see examples below).Examples:
Please note that Java'sList.empty().average() // = None List.of(1, 2, 3).average() // = Some(2.0) List.of(1.0, 10e100, 2.0, -10e100).average() // = Some(0.75) List.of(1.0, Double.NaN).average() // = NaN List.of("apple", "pear").average() // throwsDoubleStream.average()uses the Kahan summation algorithm (also known as compensated summation), which has known limitations.Vavr uses Neumaier's modification of the Kahan algorithm, which yields better results.
// = OptionalDouble(0.0) (wrong) j.u.s.DoubleStream.of(1.0, 10e100, 2.0, -10e100).average() // = Some(0.75) (correct) List.of(1.0, 10e100, 2.0, -10e100).average()- Returns:
Some(average)orNone, if there are no elements- Throws:
UnsupportedOperationException- if this elements are not numeric
-
collect
Collects all elements that are in the domain of the givenpartialFunctionby mapping the elements to typeR.More specifically, for each of this elements in iteration order first it is checked
If the elements makes it through that filter, the mapped instance is added to the result collectionpartialFunction.isDefinedAt(element)
Note:If thisR newElement = partialFunction.apply(element)Traversableis ordered (i.e. extendsOrdered, the caller ofcollecthas to ensure that the elements are comparable (i.e. extendComparable).- Type Parameters:
R- The new element type- Parameters:
partialFunction- A function that is not necessarily defined of all elements of this traversable.- Returns:
- A new
Traversableinstance containing elements of typeR - Throws:
NullPointerException- ifpartialFunctionis null
-
containsAll
Tests if this Traversable contains all given elements.The result is equivalent to
elements.isEmpty() ? true : contains(elements.head()) && containsAll(elements.tail())but implemented without recursion.- Parameters:
elements- A List of values of type T.- Returns:
- true, if this List contains all given elements, false otherwise.
- Throws:
NullPointerException- ifelementsis null
-
count
Counts the elements which satisfy the given predicate.- Parameters:
predicate- A predicate- Returns:
- A number
>= 0 - Throws:
NullPointerException- ifpredicateis null.
-
distinct
Traversable<T> distinct()Returns a new version of this which contains no duplicates. Elements are compared usingequals.- Returns:
- a new
Traversablecontaining this elements without duplicates
-
distinctBy
Returns a new version of this which contains no duplicates. Elements are compared using the givencomparator.- Parameters:
comparator- A comparator- Returns:
- a new
Traversablecontaining this elements without duplicates - Throws:
NullPointerException- ifcomparatoris null.
-
distinctBy
Returns a new version of this which contains no duplicates. Elements mapped to keys which are compared usingequals.The elements of the result are determined in the order of their occurrence - first match wins.
- Type Parameters:
U- key type- Parameters:
keyExtractor- A key extractor- Returns:
- a new
Traversablecontaining this elements without duplicates - Throws:
NullPointerException- ifkeyExtractoris null
-
drop
Drops the first n elements of this or all elements, if this length < n.- Parameters:
n- The number of elements to drop.- Returns:
- a new instance consisting of all elements of this except the first n ones, or else the empty instance, if this has less than n elements.
-
dropRight
Drops the last n elements of this or all elements, if this length < n.- Parameters:
n- The number of elements to drop.- Returns:
- a new instance consisting of all elements of this except the last n ones, or else the empty instance, if this has less than n elements.
-
dropUntil
Drops elements until the predicate holds for the current element.- Parameters:
predicate- A condition tested subsequently for this elements.- Returns:
- a new instance consisting of all elements starting from the first one which does satisfy the given predicate.
- Throws:
NullPointerException- ifpredicateis null
-
dropWhile
Drops elements while the predicate holds for the current element.Note: This is essentially the same as
dropUntil(predicate.negate()). It is intended to be used with method references, which cannot be negated directly.- Parameters:
predicate- A condition tested subsequently for this elements.- Returns:
- a new instance consisting of all elements starting from the first one which does not satisfy the given predicate.
- Throws:
NullPointerException- ifpredicateis null
-
equals
In Vavr there are four basic classes of collections:- Seq (sequential elements)
- Set (distinct elements)
- Map (indexed elements)
- Multimap (indexed collections)
- belong to the same basic collection class (Seq, Set, Map or Multimap)
- contain the same elements
- have the same element order, if the collections are of type Seq
Notes:
- No collection instance equals null, e.g. Queue(1) not equals null.
- Nulls are allowed and handled as expected, e.g. List(null, 1) equals Stream(null, 1) and HashMap((null, 1)) equals LinkedHashMap((null, 1)).
- The element order is taken into account for Seq only. E.g. List(null, 1) not equals Stream(1, null) and HashMap((null, 1), ("a", null)) equals LinkedHashMap(("a", null), (null, 1)). The reason is, that we do not know which implementations we compare when having two instances of type Map, Multimap or Set (see Liskov Substitution Principle).
- Other collection classes are equal if their types are equal and their elements are equal (in iteration order).
- Iterator equality is defined to be object reference equality.
-
existsUnique
Checks, if a unique elements exists such that the predicate holds.- Parameters:
predicate- A Predicate- Returns:
- true, if predicate holds for a unique element, false otherwise
- Throws:
NullPointerException- ifpredicateis null
-
filter
Returns a new traversable consisting of all elements which satisfy the given predicate.- Parameters:
predicate- A predicate- Returns:
- a new traversable
- Throws:
NullPointerException- ifpredicateis null
-
reject
Returns a new traversable consisting of all elements which do not satisfy the given predicate.The default implementation is equivalent to
filter(predicate.negate()- Parameters:
predicate- A predicate- Returns:
- a new traversable
- Throws:
NullPointerException- ifpredicateis null
-
find
Returns the first element of this which satisfies the given predicate.- Parameters:
predicate- A predicate.- Returns:
- Some(element) or None, where element may be null (i.e.
List.of(null).find(e -> e == null)). - Throws:
NullPointerException- ifpredicateis null
-
findLast
Returns the last element of this which satisfies the given predicate.Same as
reverse().find(predicate).- Parameters:
predicate- A predicate.- Returns:
- Some(element) or None, where element may be null (i.e.
List.of(null).find(e -> e == null)). - Throws:
NullPointerException- ifpredicateis null
-
flatMap
FlatMaps this Traversable.- Type Parameters:
U- The resulting component type.- Parameters:
mapper- A mapper- Returns:
- A new Traversable instance.
-
foldLeft
Description copied from interface:FoldableFolds this elements from the left, starting withzeroand successively callingcombine.Example:
// = "cba!" List("a", "b", "c").foldLeft("!", (xs, x) -> x + xs) -
foldRight
Description copied from interface:FoldableFolds this elements from the right, starting withzeroand successively callingcombine.Example:
// = "!cba" List("a", "b", "c").foldRight("!", (x, xs) -> xs + x) -
forEachWithIndex
Performs an action on each element. In contrast toValue.forEach(Consumer), additionally the element's index is passed to the givenaction.This is essentially the same as
iterator().zipWithIndex().forEach()but performs better because no intermediateTuple2instances are created and no boxing of int values takes place.Please note that subsequent calls to
forEachWithIndexmight lead to different iteration orders, depending on the underlyingTraversableimplementation.Please also note that
forEachWithIndexmight loop infinitely if theTraversableis lazily evaluated, likeStream.- Parameters:
action- AObjIntConsumer- Throws:
NullPointerException- ifactionis null
-
get
Gets the first value in iteration order if thisTraversableis not empty, otherwise throws.- Specified by:
getin interfaceValue<T>- Returns:
- the first value
- Throws:
NoSuchElementException- if thisTraversableis empty.
-
groupBy
Groups this elements by classifying the elements.- Type Parameters:
C- classified class type- Parameters:
classifier- A function which classifies elements into classes- Returns:
- A Map containing the grouped elements
- Throws:
NullPointerException- ifclassifieris null.- See Also:
-
grouped
Groups thisTraversableinto fixed size blocks.Let length be the length of this Iterable. Then grouped is defined as follows:
- If
this.isEmpty(), the resultingIteratoris empty. - If
size <= length, the resultingIteratorwill containlength / sizeblocks of sizesizeand maybe a non-empty block of sizelength % size, if there are remaining elements. - If
size > length, the resultingIteratorwill contain one block of sizelength.
Please note that[].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]]grouped(int)is a special case of sliding(int, int), i.e.grouped(size)is the same assliding(size, size).- Parameters:
size- a positive block size- Returns:
- A new Iterator of grouped blocks of the given size
- Throws:
IllegalArgumentException- ifsizeis negative or zero
- If
-
hasDefiniteSize
boolean hasDefiniteSize()Checks if this Traversable is known to have a finite size.This method should be implemented by classes only, i.e. not by interfaces.
- Returns:
- true, if this Traversable is known to have a finite size, false otherwise.
-
head
T head()Returns the first element of a non-empty Traversable.- Returns:
- The first element of this Traversable.
- Throws:
NoSuchElementException- if this is empty
-
headOption
-
hashCode
int hashCode()Returns the hash code of this collection.
We distinguish between two types of hashes, those for collections with predictable iteration order (like Seq) and those with arbitrary iteration order (like Set, Map and Multimap).
In all cases the hash of an empty collection is defined to be 1.
Collections with predictable iteration order are hashed as follows:
Collections with arbitrary iteration order are hashed in a way such that the hash of a fixed number of elements is independent of their iteration order.int hash = 1; for (T t : this) { hash = hash * 31 + Objects.hashCode(t); }
Please note that the particular hashing algorithms may change in a future version of Vavr.int hash = 1; for (T t : this) { hash += Objects.hashCode(t); }
Generally, hash codes of collections aren't cached in Vavr (opposed to the size/length). Storing hash codes in order to reduce the time complexity would increase the memory footprint. Persistent collections are built upon tree structures, it allows us to implement efficient memory sharing. A drawback of tree structures is that they make it necessary to store collection attributes at each tree node (read: element).
The computation of the hash code is linear in time, i.e. O(n). If the hash code of a collection is re-calculated often, e.g. when using a List as HashMap key, we might want to cache the hash code. This can be achieved by simply using a wrapper class, which is not included in Vavr but could be implemented like this: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; } else if (key != null && o instanceof Hashed) { final Hashed that = (Hashed) o; return key.equals(that.key); } else { return false; } } @Override public int hashCode() { return hashCode.get(); } @Override public String toString() { return "Hashed(" + (key == null ? "null" : key.toString()) + ")"; } } -
init
Traversable<T> init()Dual of tail(), returning all elements except the last.- Returns:
- a new instance containing all elements except the last.
- Throws:
UnsupportedOperationException- if this is empty
-
initOption
Dual of tailOption(), returning all elements except the last asOption.- Returns:
Some(traversable)orNoneif this is empty.
-
isDistinct
default boolean isDistinct()Checks if this Traversable may consist of distinct elements only.- Returns:
- true if this Traversable may consist of distinct elements only, false otherwise.
-
isEmpty
-
isOrdered
default boolean isOrdered()Checks if this Traversable is ordered- Returns:
- true, if this Traversable is ordered, false otherwise.
-
isSequential
default boolean isSequential()Checks if the elements of this Traversable appear in encounter order.- Returns:
- true, if the insertion order of elements is preserved, false otherwise.
-
isSingleValued
default boolean isSingleValued()Each of Vavr's collections may contain more than one element.- Specified by:
isSingleValuedin interfaceValue<T>- Returns:
false
-
isTraversableAgain
boolean isTraversableAgain()Checks if this Traversable can be repeatedly traversed.This method should be implemented by classes only, i.e. not by interfaces.
- Returns:
- true, if this Traversable is known to be traversable repeatedly, false otherwise.
-
iterator
-
last
T last()Dual of head(), returning the last element.- Returns:
- the last element.
- Throws:
NoSuchElementException- is this is empty
-
lastOption
Dual of headOption(), returning the last element asOption.- Returns:
Some(element)orNoneif this is empty.
-
length
int length()Computes the number of elements of this Traversable.Same as
size().- Returns:
- the number of elements
-
map
Maps the elements of thisTraversableto elements of a new type preserving their order, if any.- Specified by:
mapin interfaceValue<T>- Type Parameters:
U- Component type of the target Traversable- Parameters:
mapper- A mapper.- Returns:
- a mapped Traversable
- Throws:
NullPointerException- ifmapperis null
-
max
Calculates the maximum of this elements according to their natural order. Especially the underlying order of sorted collections is not taken into account.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- Returns:
Some(maximum)of this elements orNoneif this is empty- Throws:
NullPointerException- if an element is nullClassCastException- if the elements do not have a natural order, i.e. they do not implement Comparable
-
maxBy
Calculates the maximum of this elements using a specific comparator.- Parameters:
comparator- A non-null element comparator- Returns:
Some(maximum)of this elements orNoneif this is empty- Throws:
NullPointerException- ifcomparatoris null
-
maxBy
Calculates the maximum of this elements within the co-domain of a specific function.- Type Parameters:
U- The type where elements are compared- Parameters:
f- A function that maps this elements to comparable elements- Returns:
- The element of type T which is the maximum within U
- Throws:
NullPointerException- iffis null.
-
min
Calculates the minimum of this elements according to their natural order in O(n). Especially the underlying order of sorted collections is not taken into account.Examples:
There is an exception forList.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() // throwsDoubleandFloat: The minimum is defined to beNaNif this containsNaN. According to the natural orderNaNwould be the maximum element instead.- Returns:
Some(minimum)of this elements orNoneif this is empty- Throws:
NullPointerException- if an element is nullClassCastException- if the elements do not have a natural order, i.e. they do not implement Comparable
-
minBy
Calculates the minimum of this elements using a specific comparator.- Parameters:
comparator- A non-null element comparator- Returns:
Some(minimum)of this elements orNoneif this is empty- Throws:
NullPointerException- ifcomparatoris null
-
minBy
Calculates the minimum of this elements within the co-domain of a specific function.- Type Parameters:
U- The type where elements are compared- Parameters:
f- A function that maps this elements to comparable elements- Returns:
- The element of type T which is the minimum within U
- Throws:
NullPointerException- iffis null.
-
mkCharSeq
-
mkCharSeq
Joins the string representations of this elements using a specific delimiter.This has the same effect as calling
mkCharSeq("", delimiter, "").- Parameters:
delimiter- A delimiter string put between string representations of elements of this- Returns:
- A new
CharSeq
-
mkCharSeq
Joins the string representations of this elements using a specific delimiter, prefix and suffix.Example:
List.of("a", "b", "c").mkCharSeq("Chars(", ", ", ")") = CharSeq.of("Chars(a, b, c))" -
mkString
Joins the elements of this by concatenating their string representations.This has the same effect as calling
mkString("", "", "").- Returns:
- a new String
-
mkString
Joins the string representations of this elements using a specific delimiter.This has the same effect as calling
mkString("", delimiter, "").- Parameters:
delimiter- A delimiter string put between string representations of elements of this- Returns:
- A new String
-
mkString
Joins the string representations of this elements using a specific delimiter, prefix and suffix.Example:
List.of("a", "b", "c").mkString("Chars(", ", ", ")") = "Chars(a, b, c)"- Parameters:
prefix- prefix of the resulting stringdelimiter- A delimiter string put between string representations of elements of thissuffix- suffix of the resulting string- Returns:
- a new String
-
nonEmpty
default boolean nonEmpty()Checks, thisTraversableis not empty.The call is equivalent to
!isEmpty().- Returns:
- true, if an underlying value is present, false otherwise.
-
orElse
Returns thisTraversableif it is nonempty, otherwise return the alternative.- Parameters:
other- An alternativeTraversable- Returns:
- this
Traversableif it is nonempty, otherwise return the alternative.
-
orElse
Returns thisTraversableif it is nonempty, otherwise return the result of evaluating supplier.- Parameters:
supplier- An alternativeTraversablesupplier- Returns:
- this
Traversableif it is nonempty, otherwise return the result of evaluating supplier.
-
partition
Tuple2<? extends Traversable<T>, ? extends Traversable<T>> partition(Predicate<? super T> predicate) Creates a partition of thisTraversableby splitting this elements in two in distinct traversables according to a predicate.- Parameters:
predicate- A predicate which classifies an element if it is in the first or the second traversable.- Returns:
- A disjoint union of two traversables. The first
Traversablecontains all elements that satisfy the givenpredicate, the secondTraversablecontains all elements that don't. The original order of elements is preserved. - Throws:
NullPointerException- if predicate is 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 this elements. Supported component types areByte,Double,Float,Integer,Long,Short,BigIntegerandBigDecimal.Examples:
Please also seeList.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() // throwsFoldable.fold(Object, BiFunction), a way to do a type-safe multiplication of elements.- Returns:
- a
Numberrepresenting the sum of this elements - Throws:
UnsupportedOperationException- if this elements are not numeric
-
reduceLeft
Accumulates the elements of this Traversable by successively calling the given operationopfrom the left.- Specified by:
reduceLeftin interfaceFoldable<T>- Parameters:
op- A BiFunction of type T- Returns:
- the reduced value.
- Throws:
NoSuchElementException- if this is emptyNullPointerException- ifopis null
-
reduceLeftOption
Shortcut forisEmpty() ? Option.none() : Option.some(reduceLeft(op)).- Specified by:
reduceLeftOptionin interfaceFoldable<T>- Parameters:
op- A BiFunction of type T- Returns:
- a reduced value
- Throws:
NullPointerException- ifopis null
-
reduceRight
Accumulates the elements of this Traversable by successively calling the given operationopfrom the right.- Specified by:
reduceRightin interfaceFoldable<T>- Parameters:
op- An operation of type T- Returns:
- the reduced value.
- Throws:
NoSuchElementException- if this is emptyNullPointerException- ifopis null
-
reduceRightOption
Shortcut forisEmpty() ? Option.none() : Option.some(reduceRight(op)).- Specified by:
reduceRightOptionin interfaceFoldable<T>- Parameters:
op- An operation of type T- Returns:
- a reduced value
- Throws:
NullPointerException- ifopis null
-
replace
Replaces the first occurrence (if exists) of the given currentElement with newElement.- Parameters:
currentElement- An element to be substituted.newElement- A replacement for currentElement.- Returns:
- a Traversable containing all elements of this where the first occurrence of currentElement is replaced with newElement.
-
replaceAll
Replaces all occurrences of the given currentElement with newElement.- Parameters:
currentElement- An element to be substituted.newElement- A replacement for currentElement.- Returns:
- a Traversable containing all elements of this where all occurrences of currentElement are replaced with newElement.
-
retainAll
Keeps all occurrences of the given elements from this.- Parameters:
elements- Elements to be kept.- Returns:
- a Traversable containing all occurrences of the given elements.
- Throws:
NullPointerException- ifelementsis null
-
scan
Computes a prefix scan of the elements of the collection. Note: The neutral element z may be applied more than once.- Parameters:
zero- neutral element for the operator opoperation- the associative operator for the scan- Returns:
- a new traversable collection containing the prefix scan of the elements in this traversable collection
- Throws:
NullPointerException- ifoperationis null.
-
scanLeft
Produces a collection containing cumulative results of applying the operator going left to right. Note: will not terminate for infinite-sized collections. Note: might return different results for different runs, unless the underlying collection type is ordered.- Type Parameters:
U- the type of the elements in the resulting collection- Parameters:
zero- the initial valueoperation- the binary operator applied to the intermediate result and the element- Returns:
- collection with intermediate results
- Throws:
NullPointerException- ifoperationis null.
-
scanRight
Produces a collection containing cumulative results of applying the operator going right to left. The head of the collection is the last cumulative result. Note: will not terminate for infinite-sized collections. Note: might return different results for different runs, unless the underlying collection type is ordered.- Type Parameters:
U- the type of the elements in the resulting collection- Parameters:
zero- the initial valueoperation- the binary operator applied to the intermediate result and the element- Returns:
- collection with intermediate results
- Throws:
NullPointerException- ifoperationis null.
-
single
Returns the single element of this Traversable or throws, if this is empty or contains more than one element.- Returns:
- the single element from the Traversable
- Throws:
NoSuchElementException- if the Traversable does not contain a single element.
-
singleOption
-
size
default int size()Computes the number of elements of this Traversable.Same as
length().- Returns:
- the number of elements
-
slideBy
Slides a non-overlapping window of a variable size over thisTraversable.Each window contains elements with the same class, as determined by
classifier. Two consecutive values in thisTraversablewill be in the same window only ifclassifierreturns equal values for them. Otherwise, the values will constitute the last element of the previous window and the first element of the next window.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 which classifies elements into classes- Returns:
- A new Iterator of windows of the grouped elements
- Throws:
NullPointerException- ifclassifieris null.
-
sliding
Slides a window of a specificsizeand step size 1 over thisTraversableby callingsliding(int, int).- Parameters:
size- a positive window size- Returns:
- a new Iterator of windows of a specific size using step size 1
- Throws:
IllegalArgumentException- ifsizeis negative or zero
-
sliding
Slides a window of a specificsizeandstepsize over 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:
- a new Iterator of windows of a specific size using a specific step size
- Throws:
IllegalArgumentException- ifsizeorstepare negative or zero
-
span
Returns a tuple where the first element is the longest prefix of elements that satisfy the givenpredicateand the second element is the remainder.- Parameters:
predicate- A predicate.- Returns:
- a
Tuplecontaining the longest prefix of elements that satisfy p and the remainder. - Throws:
NullPointerException- ifpredicateis null
-
spliterator
- Specified by:
spliteratorin interfaceIterable<T>- Specified by:
spliteratorin interfaceValue<T>
-
sum
Calculates the sum of this elements. Supported component types areByte,Double,Float,Integer,Long,Short,BigIntegerandBigDecimal.Examples:
Please also seeList.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() // throwsFoldable.fold(Object, BiFunction), a way to do a type-safe summation of elements.- Returns:
- a
Numberrepresenting the sum of this elements - Throws:
UnsupportedOperationException- if this elements are not numeric
-
tail
Traversable<T> tail()Drops the first element of a non-empty Traversable.- Returns:
- A new instance of Traversable containing all elements except the first.
- Throws:
UnsupportedOperationException- if this is empty
-
tailOption
Option<? extends Traversable<T>> tailOption()Drops the first element of a non-empty Traversable and returns anOption.- Returns:
Some(traversable)orNoneif this is empty.
-
take
Takes the first n elements of this or all elements, if this length < n.The result is equivalent to
sublist(0, max(0, min(length(), n)))but does not throw ifn < 0orn > length().In the case of
n < 0the empty instance is returned, in the case ofn > length()this is returned.- Parameters:
n- The number of elements to take.- Returns:
- A new instance consisting of the first n elements of this or all elements, if this has less than n elements.
-
takeRight
Takes the last n elements of this or all elements, if this length < n.The result is equivalent to
sublist(max(0, min(length(), length() - n)), n), i.e. takeRight will not throw ifn < 0orn > length().In the case of
n < 0the empty instance is returned, in the case ofn > length()this is returned.- Parameters:
n- The number of elements to take.- Returns:
- A new instance consisting of the last n elements of this or all elements, if this has less than n elements.
-
takeUntil
Takes elements until the predicate holds for the current element.Note: This is essentially the same as
takeWhile(predicate.negate()). It is intended to be used with method references, which cannot be negated directly.- Parameters:
predicate- A condition tested subsequently for this elements.- Returns:
- a new instance consisting of all elements before the first one which does satisfy the given predicate.
- Throws:
NullPointerException- ifpredicateis null
-
takeWhile
Takes elements while the predicate holds for the current element.- Parameters:
predicate- A condition tested subsequently for the contained elements.- Returns:
- a new instance consisting of all elements before the first one which does not satisfy the given predicate.
- Throws:
NullPointerException- ifpredicateis null
-
unzip
<T1,T2> Tuple2<? extends Traversable<T1>, ? extends Traversable<T2>> unzip(Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper) Unzips this elements by mapping this elements to pairs which are subsequently split into two distinct sets.- Type Parameters:
T1- 1st element type of a pair returned by unzipperT2- 2nd element type of a pair returned by unzipper- Parameters:
unzipper- a function which converts elements of this to pairs- Returns:
- A pair of set containing elements split by unzipper
- Throws:
NullPointerException- ifunzipperis null
-
unzip3
<T1,T2, Tuple3<? extends Traversable<T1>, ? extends Traversable<T2>, ? extends Traversable<T3>> unzip3T3> (Function<? super T, Tuple3<? extends T1, ? extends T2, ? extends T3>> unzipper) Unzips this elements by mapping this elements to triples which are subsequently split into three distinct sets.- Type Parameters:
T1- 1st element type of a triplet returned by unzipperT2- 2nd element type of a triplet returned by unzipperT3- 3rd element type of a triplet returned by unzipper- Parameters:
unzipper- a function which converts elements of this to pairs- Returns:
- A triplet of set containing elements split by unzipper
- Throws:
NullPointerException- ifunzipperis null
-
zip
Returns a traversable formed from this traversable and another Iterable collection by combining corresponding elements in pairs. If one of the two iterables is longer than the other, its remaining elements are ignored.The length of the returned traversable is the minimum of the lengths of this traversable and
thatiterable.- Type Parameters:
U- The type of the second half of the returned pairs.- Parameters:
that- The Iterable providing the second half of each result pair.- Returns:
- a new traversable containing pairs consisting of corresponding elements of this traversable and
thatiterable. - Throws:
NullPointerException- ifthatis null
-
zipAll
Returns a traversable formed from this traversable and another Iterable by combining corresponding elements in pairs. If one of the two collections is shorter than the other, placeholder elements are used to extend the shorter collection to the length of the longer.The length of the returned traversable is the maximum of the lengths of this traversable and
thatiterable.Special case: if this traversable is shorter than that elements, and that elements contains duplicates, the resulting traversable may be shorter than the maximum of the lengths of this and that because a traversable contains an element at most once.
If this Traversable is shorter than that, thisElem values are used to fill the result. If that is shorter than this Traversable, thatElem values are used to fill the result.
- Type Parameters:
U- The type of the second half of the returned pairs.- Parameters:
that- The Iterable providing the second half of each result pair.thisElem- The element to be used to fill up the result if this traversable is shorter than that.thatElem- The element to be used to fill up the result if that is shorter than this traversable.- Returns:
- A new traversable containing pairs consisting of corresponding elements of this traversable and that.
- Throws:
NullPointerException- ifthatis null
-
zipWith
<U,R> Traversable<R> zipWith(Iterable<? extends U> that, BiFunction<? super T, ? super U, ? extends R> mapper) Returns a traversable formed from this traversable and another Iterable collection by mapping elements. If one of the two iterables is longer than the other, its remaining elements are ignored.The length of the returned traversable is the minimum of the lengths of this traversable and
thatiterable.- Type Parameters:
U- The type of the second parameter of the mapper.R- The type of the mapped elements.- Parameters:
that- The Iterable providing the second parameter of the mapper.mapper- a mapper.- Returns:
- a new traversable containing mapped elements of this traversable and
thatiterable. - Throws:
NullPointerException- ifthatormapperis null
-
zipWithIndex
Traversable<Tuple2<T,Integer>> zipWithIndex()Zips this traversable with its indices.- Returns:
- A new traversable containing all elements of this traversable paired with their index, starting with 0.
-
zipWithIndex
Zips this traversable with its indices by applying mapper provided.- Type Parameters:
U- The type of the mapped elements.- Parameters:
mapper- a mapper.- Returns:
- a new traversable containing elements of this traversable, zipped with indices, and mapped with mapper provided.
- Throws:
NullPointerException- ifmapperis null
-