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
public interface Traversable<T> extends Foldable<T>, Value<T>
An interface for inherently recursive, multi-valued data structures. The order of elements is determined byIterable.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
All Methods Static Methods Instance Methods Abstract Methods Default Methods Modifier and Type Method Description default <K> Option<Map<K,T>>arrangeBy(java.util.function.Function<? super T,? extends K> getKey)Matches each element with a unique key that you extract from it.default Option<java.lang.Double>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(java.lang.Iterable<? extends T> elements)Tests if this Traversable contains all given elements.default intcount(java.util.function.Predicate<? super T> predicate)Counts the elements which satisfy the given predicate.Traversable<T>distinct()Returns a new version of this which contains no duplicates.Traversable<T>distinctBy(java.util.Comparator<? super T> comparator)Returns a new version of this which contains no duplicates.<U> Traversable<T>distinctBy(java.util.function.Function<? super T,? extends U> keyExtractor)Returns a new version of this which contains no duplicates.Traversable<T>drop(int n)Drops the first n elements of this or all elements, if this length < n.Traversable<T>dropRight(int n)Drops the last n elements of this or all elements, if this length < n.Traversable<T>dropUntil(java.util.function.Predicate<? super T> predicate)Drops elements until the predicate holds for the current element.Traversable<T>dropWhile(java.util.function.Predicate<? super T> predicate)Drops elements while the predicate holds for the current element.booleanequals(java.lang.Object obj)In 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(java.util.function.Predicate<? super T> predicate)Checks, if a unique elements exists such that the predicate holds.Traversable<T>filter(java.util.function.Predicate<? super T> predicate)Returns a new traversable consisting of all elements which satisfy the given predicate.default Option<T>find(java.util.function.Predicate<? super T> predicate)Returns the first element of this which satisfies the given predicate.default Option<T>findLast(java.util.function.Predicate<? super T> predicate)Returns the last element of this which satisfies the given predicate.<U> Traversable<U>flatMap(java.util.function.Function<? super T,? extends java.lang.Iterable<? extends U>> mapper)FlatMaps this Traversable.default <U> UfoldLeft(U zero, java.util.function.BiFunction<? super U,? super T,? extends U> f)Folds this elements from the left, starting withzeroand successively callingcombine.<U> UfoldRight(U zero, java.util.function.BiFunction<? super T,? super U,? extends U> f)Folds this elements from the right, starting withzeroand successively callingcombine.default voidforEachWithIndex(java.util.function.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>>groupBy(java.util.function.Function<? super T,? extends C> classifier)Groups this elements by classifying the elements.Iterator<? extends Traversable<T>>grouped(int size)Groups thisTraversableinto fixed size blocks.booleanhasDefiniteSize()Checks if this Traversable is known to have a finite size.inthashCode()Returns the hash code of this collection.Thead()Returns the first element of a non-empty Traversable.default Option<T>headOption()Returns the first element of a non-empty Traversable asOption.Traversable<T>init()Dual of tail(), returning all elements except the last.default Option<? extends Traversable<T>>initOption()Dual of tailOption(), returning all elements except the last asOption.default booleanisDistinct()Checks if this Traversable may consist of distinct elements only.default booleanisEmpty()Checks if this Traversable is empty.default booleanisOrdered()Checks if this Traversable is ordereddefault booleanisSequential()Checks if the elements of this Traversable appear in encounter order.default booleanisSingleValued()Each of Vavr's collections may contain more than one element.booleanisTraversableAgain()Checks if this Traversable can be repeatedly traversed.default Iterator<T>iterator()An iterator by means of head() and tail().Tlast()Dual of head(), returning the last element.default Option<T>lastOption()Dual of headOption(), returning the last element asOption.intlength()Computes the number of elements of this Traversable.<U> Traversable<U>map(java.util.function.Function<? super T,? extends U> mapper)Maps the elements of thisTraversableto elements of a new type preserving their order, if any.default Option<T>max()Calculates the maximum of this elements according to their natural order.default Option<T>maxBy(java.util.Comparator<? super T> comparator)Calculates the maximum of this elements using a specific comparator.default <U extends java.lang.Comparable<? super U>>
Option<T>maxBy(java.util.function.Function<? super T,? extends U> f)Calculates the maximum of this elements within the co-domain of a specific function.default Option<T>min()Calculates the minimum of this elements according to their natural order in O(n).default Option<T>minBy(java.util.Comparator<? super T> comparator)Calculates the minimum of this elements using a specific comparator.default <U extends java.lang.Comparable<? super U>>
Option<T>minBy(java.util.function.Function<? super T,? extends U> f)Calculates the minimum of this elements within the co-domain of a specific function.default CharSeqmkCharSeq()Joins the elements of this by concatenating their string representations.default CharSeqmkCharSeq(java.lang.CharSequence delimiter)Joins the string representations of this elements using a specific delimiter.default CharSeqmkCharSeq(java.lang.CharSequence prefix, java.lang.CharSequence delimiter, java.lang.CharSequence suffix)Joins the string representations of this elements using a specific delimiter, prefix and suffix.default java.lang.StringmkString()Joins the elements of this by concatenating their string representations.default java.lang.StringmkString(java.lang.CharSequence delimiter)Joins the string representations of this elements using a specific delimiter.default java.lang.StringmkString(java.lang.CharSequence prefix, java.lang.CharSequence delimiter, java.lang.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.Traversable<T>orElse(java.lang.Iterable<? extends T> other)Returns thisTraversableif it is nonempty, otherwise return the alternative.Traversable<T>orElse(java.util.function.Supplier<? extends java.lang.Iterable<? extends T>> supplier)Returns thisTraversableif it is nonempty, otherwise return the result of evaluating supplier.Tuple2<? extends Traversable<T>,? extends Traversable<T>>partition(java.util.function.Predicate<? super T> predicate)Creates a partition of thisTraversableby splitting this elements in two in distinct traversables according to a predicate.Traversable<T>peek(java.util.function.Consumer<? super T> action)Performs the givenactionon the first element if this is an eager implementation.default java.lang.Numberproduct()Calculates the product of this elements.default TreduceLeft(java.util.function.BiFunction<? super T,? super T,? extends T> op)Accumulates the elements of this Traversable by successively calling the given operationopfrom the left.default Option<T>reduceLeftOption(java.util.function.BiFunction<? super T,? super T,? extends T> op)Shortcut forisEmpty() ? Option.none() : Option.some(reduceLeft(op)).default TreduceRight(java.util.function.BiFunction<? super T,? super T,? extends T> op)Accumulates the elements of this Traversable by successively calling the given operationopfrom the right.default Option<T>reduceRightOption(java.util.function.BiFunction<? super T,? super T,? extends T> op)Shortcut forisEmpty() ? Option.none() : Option.some(reduceRight(op)).default Traversable<T>reject(java.util.function.Predicate<? super T> predicate)Returns a new traversable consisting of all elements which do not satisfy the given predicate.Traversable<T>replace(T currentElement, T newElement)Replaces the first occurrence (if exists) of the given currentElement with newElement.Traversable<T>replaceAll(T currentElement, T newElement)Replaces all occurrences of the given currentElement with newElement.Traversable<T>retainAll(java.lang.Iterable<? extends T> elements)Keeps all occurrences of the given elements from this.Traversable<T>scan(T zero, java.util.function.BiFunction<? super T,? super T,? extends T> operation)Computes a prefix scan of the elements of the collection.<U> Traversable<U>scanLeft(U zero, java.util.function.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, java.util.function.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.default Option<T>singleOption()Returns the only element of a Traversable asOption.default intsize()Computes the number of elements of this Traversable.Iterator<? extends Traversable<T>>slideBy(java.util.function.Function<? super T,?> classifier)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>>span(java.util.function.Predicate<? super T> predicate)Returns a tuple where the first element is the longest prefix of elements that satisfy the givenpredicateand the second element is the remainder.default java.util.Spliterator<T>spliterator()default java.lang.Numbersum()Calculates the sum of this elements.Traversable<T>tail()Drops the first element of a non-empty Traversable.Option<? extends Traversable<T>>tailOption()Drops the first element of a non-empty Traversable and returns anOption.Traversable<T>take(int n)Takes the first n elements of this or all elements, if this length < n.Traversable<T>takeRight(int n)Takes the last n elements of this or all elements, if this length < n.Traversable<T>takeUntil(java.util.function.Predicate<? super T> predicate)Takes elements until the predicate holds for the current element.Traversable<T>takeWhile(java.util.function.Predicate<? super T> predicate)Takes elements while the predicate holds for the current element.<T1,T2>
Tuple2<? extends Traversable<T1>,? extends Traversable<T2>>unzip(java.util.function.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.<T1,T2,T3>
Tuple3<? extends Traversable<T1>,? extends Traversable<T2>,? extends Traversable<T3>>unzip3(java.util.function.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.<U> Traversable<Tuple2<T,U>>zip(java.lang.Iterable<? extends U> that)Returns a traversable formed from this traversable and another Iterable collection by combining corresponding elements in pairs.<U> Traversable<Tuple2<T,U>>zipAll(java.lang.Iterable<? extends U> that, T thisElem, U thatElem)Returns a traversable formed from this traversable and another Iterable by combining corresponding elements in pairs.<U,R>
Traversable<R>zipWith(java.lang.Iterable<? extends U> that, java.util.function.BiFunction<? super T,? super U,? extends R> mapper)Returns a traversable formed from this traversable and another Iterable collection by mapping elements.Traversable<Tuple2<T,java.lang.Integer>>zipWithIndex()Zips this traversable with its indices.<U> Traversable<U>zipWithIndex(java.util.function.BiFunction<? super T,? super java.lang.Integer,? extends U> mapper)Zips this traversable with its indices by applying mapper provided.-
Methods inherited from interface io.vavr.collection.Foldable
fold, reduce, reduceOption
-
Methods 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 Detail
-
narrow
static <T> Traversable<T> narrow(Traversable<? extends T> traversable)
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
default <K> Option<Map<K,T>> arrangeBy(java.util.function.Function<? super T,? extends K> getKey)
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:
java.lang.NullPointerException- ifgetKeyis null.- See Also:
groupBy(Function)
-
average
default Option<java.lang.Double> 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:
java.lang.UnsupportedOperationException- if this elements are not numeric
-
collect
<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.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:
java.lang.NullPointerException- ifpartialFunctionis null
-
containsAll
default boolean containsAll(java.lang.Iterable<? extends T> elements)
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:
java.lang.NullPointerException- ifelementsis null
-
count
default int count(java.util.function.Predicate<? super T> predicate)
Counts the elements which satisfy the given predicate.- Parameters:
predicate- A predicate- Returns:
- A number
>= 0 - Throws:
java.lang.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
Traversable<T> distinctBy(java.util.Comparator<? super T> comparator)
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:
java.lang.NullPointerException- ifcomparatoris null.
-
distinctBy
<U> Traversable<T> distinctBy(java.util.function.Function<? super T,? extends U> keyExtractor)
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:
java.lang.NullPointerException- ifkeyExtractoris null
-
drop
Traversable<T> drop(int n)
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
Traversable<T> dropRight(int n)
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
Traversable<T> dropUntil(java.util.function.Predicate<? super T> predicate)
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:
java.lang.NullPointerException- ifpredicateis null
-
dropWhile
Traversable<T> dropWhile(java.util.function.Predicate<? super T> predicate)
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:
java.lang.NullPointerException- ifpredicateis null
-
equals
boolean equals(java.lang.Object obj)
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
default boolean existsUnique(java.util.function.Predicate<? super T> predicate)
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:
java.lang.NullPointerException- ifpredicateis null
-
filter
Traversable<T> filter(java.util.function.Predicate<? super T> predicate)
Returns a new traversable consisting of all elements which satisfy the given predicate.- Parameters:
predicate- A predicate- Returns:
- a new traversable
- Throws:
java.lang.NullPointerException- ifpredicateis null
-
reject
default Traversable<T> reject(java.util.function.Predicate<? super T> predicate)
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:
java.lang.NullPointerException- ifpredicateis null
-
find
default Option<T> find(java.util.function.Predicate<? super T> predicate)
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:
java.lang.NullPointerException- ifpredicateis null
-
findLast
default Option<T> findLast(java.util.function.Predicate<? super T> predicate)
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:
java.lang.NullPointerException- ifpredicateis null
-
flatMap
<U> Traversable<U> flatMap(java.util.function.Function<? super T,? extends java.lang.Iterable<? extends U>> mapper)
FlatMaps this Traversable.- Type Parameters:
U- The resulting component type.- Parameters:
mapper- A mapper- Returns:
- A new Traversable instance.
-
foldLeft
default <U> U foldLeft(U zero, java.util.function.BiFunction<? super U,? super T,? extends U> f)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
<U> U foldRight(U zero, java.util.function.BiFunction<? super T,? super U,? extends U> f)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
default void forEachWithIndex(java.util.function.ObjIntConsumer<? super T> action)
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:
java.lang.NullPointerException- ifactionis null
-
get
default T get()
Gets the first value in iteration order if thisTraversableis not empty, otherwise throws.
-
groupBy
<C> Map<C,? extends Traversable<T>> groupBy(java.util.function.Function<? super T,? extends C> classifier)
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:
java.lang.NullPointerException- ifclassifieris null.- See Also:
arrangeBy(Function)
-
grouped
Iterator<? extends Traversable<T>> grouped(int size)
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:
java.lang.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:
java.util.NoSuchElementException- if this is empty
-
headOption
default Option<T> headOption()
Returns the first element of a non-empty Traversable asOption.- Returns:
Some(element)orNoneif this is empty.
-
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:
java.lang.UnsupportedOperationException- if this is empty
-
initOption
default Option<? extends Traversable<T>> 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
default boolean isEmpty()
Checks if this Traversable is empty.
-
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
default Iterator<T> iterator()
An iterator by means of head() and tail(). Subclasses may want to override this method.
-
last
T last()
Dual of head(), returning the last element.- Returns:
- the last element.
- Throws:
java.util.NoSuchElementException- is this is empty
-
lastOption
default Option<T> 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
<U> Traversable<U> map(java.util.function.Function<? super T,? extends U> mapper)
Maps the elements of thisTraversableto elements of a new type preserving their order, if any.
-
max
default Option<T> 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:
java.lang.NullPointerException- if an element is nulljava.lang.ClassCastException- if the elements do not have a natural order, i.e. they do not implement Comparable
-
maxBy
default Option<T> maxBy(java.util.Comparator<? super T> comparator)
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:
java.lang.NullPointerException- ifcomparatoris null
-
maxBy
default <U extends java.lang.Comparable<? super U>> Option<T> maxBy(java.util.function.Function<? super T,? extends U> f)
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:
java.lang.NullPointerException- iffis null.
-
min
default Option<T> 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:
java.lang.NullPointerException- if an element is nulljava.lang.ClassCastException- if the elements do not have a natural order, i.e. they do not implement Comparable
-
minBy
default Option<T> minBy(java.util.Comparator<? super T> comparator)
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:
java.lang.NullPointerException- ifcomparatoris null
-
minBy
default <U extends java.lang.Comparable<? super U>> Option<T> minBy(java.util.function.Function<? super T,? extends U> f)
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:
java.lang.NullPointerException- iffis null.
-
mkCharSeq
default CharSeq mkCharSeq()
Joins the elements of this by concatenating their string representations.This has the same effect as calling
mkCharSeq("", "", "").- Returns:
- a new
CharSeq
-
mkCharSeq
default CharSeq mkCharSeq(java.lang.CharSequence delimiter)
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
default CharSeq mkCharSeq(java.lang.CharSequence prefix, java.lang.CharSequence delimiter, java.lang.CharSequence suffix)
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
default java.lang.String mkString()
Joins the elements of this by concatenating their string representations.This has the same effect as calling
mkString("", "", "").- Returns:
- a new String
-
mkString
default java.lang.String mkString(java.lang.CharSequence delimiter)
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
default java.lang.String mkString(java.lang.CharSequence prefix, java.lang.CharSequence delimiter, java.lang.CharSequence suffix)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
Traversable<T> orElse(java.lang.Iterable<? extends T> other)
Returns thisTraversableif it is nonempty, otherwise return the alternative.- Parameters:
other- An alternativeTraversable- Returns:
- this
Traversableif it is nonempty, otherwise return the alternative.
-
orElse
Traversable<T> orElse(java.util.function.Supplier<? extends java.lang.Iterable<? extends T>> supplier)
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(java.util.function.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:
java.lang.NullPointerException- if predicate is null
-
peek
Traversable<T> peek(java.util.function.Consumer<? super T> action)
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
default java.lang.Number 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:
java.lang.UnsupportedOperationException- if this elements are not numeric
-
reduceLeft
default T reduceLeft(java.util.function.BiFunction<? super T,? super T,? extends T> op)
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:
java.util.NoSuchElementException- if this is emptyjava.lang.NullPointerException- ifopis null
-
reduceLeftOption
default Option<T> reduceLeftOption(java.util.function.BiFunction<? super T,? super T,? extends T> op)
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:
java.lang.NullPointerException- ifopis null
-
reduceRight
default T reduceRight(java.util.function.BiFunction<? super T,? super T,? extends T> op)
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:
java.util.NoSuchElementException- if this is emptyjava.lang.NullPointerException- ifopis null
-
reduceRightOption
default Option<T> reduceRightOption(java.util.function.BiFunction<? super T,? super T,? extends T> op)
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:
java.lang.NullPointerException- ifopis null
-
replace
Traversable<T> replace(T currentElement, T newElement)
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
Traversable<T> replaceAll(T currentElement, T newElement)
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
Traversable<T> retainAll(java.lang.Iterable<? extends T> elements)
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:
java.lang.NullPointerException- ifelementsis null
-
scan
Traversable<T> scan(T zero, java.util.function.BiFunction<? super T,? super T,? extends T> operation)
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:
java.lang.NullPointerException- ifoperationis null.
-
scanLeft
<U> Traversable<U> scanLeft(U zero, java.util.function.BiFunction<? super U,? super T,? extends U> operation)
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:
java.lang.NullPointerException- ifoperationis null.
-
scanRight
<U> Traversable<U> scanRight(U zero, java.util.function.BiFunction<? super T,? super U,? extends U> operation)
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:
java.lang.NullPointerException- ifoperationis null.
-
single
default T 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:
java.util.NoSuchElementException- if the Traversable does not contain a single element.
-
singleOption
default Option<T> singleOption()
Returns the only element of a Traversable asOption.- Returns:
Some(element)orNoneif the Traversable does not contain a single element.
-
size
default int size()
Computes the number of elements of this Traversable.Same as
length().- Returns:
- the number of elements
-
slideBy
Iterator<? extends Traversable<T>> slideBy(java.util.function.Function<? super T,?> classifier)
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:
java.lang.NullPointerException- ifclassifieris null.
-
sliding
Iterator<? extends Traversable<T>> sliding(int size)
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:
java.lang.IllegalArgumentException- ifsizeis negative or zero
-
sliding
Iterator<? extends Traversable<T>> sliding(int size, int step)
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:
java.lang.IllegalArgumentException- ifsizeorstepare negative or zero
-
span
Tuple2<? extends Traversable<T>,? extends Traversable<T>> span(java.util.function.Predicate<? super T> predicate)
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:
java.lang.NullPointerException- ifpredicateis null
-
spliterator
default java.util.Spliterator<T> spliterator()
- Specified by:
spliteratorin interfacejava.lang.Iterable<T>- Specified by:
spliteratorin interfaceValue<T>
-
sum
default java.lang.Number 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:
java.lang.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:
java.lang.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
Traversable<T> take(int n)
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
Traversable<T> takeRight(int n)
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
Traversable<T> takeUntil(java.util.function.Predicate<? super T> predicate)
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:
java.lang.NullPointerException- ifpredicateis null
-
takeWhile
Traversable<T> takeWhile(java.util.function.Predicate<? super T> predicate)
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:
java.lang.NullPointerException- ifpredicateis null
-
unzip
<T1,T2> Tuple2<? extends Traversable<T1>,? extends Traversable<T2>> unzip(java.util.function.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:
java.lang.NullPointerException- ifunzipperis null
-
unzip3
<T1,T2,T3> Tuple3<? extends Traversable<T1>,? extends Traversable<T2>,? extends Traversable<T3>> unzip3(java.util.function.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:
java.lang.NullPointerException- ifunzipperis null
-
zip
<U> Traversable<Tuple2<T,U>> zip(java.lang.Iterable<? extends U> that)
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:
java.lang.NullPointerException- ifthatis null
-
zipAll
<U> Traversable<Tuple2<T,U>> zipAll(java.lang.Iterable<? extends U> that, T thisElem, U thatElem)
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:
java.lang.NullPointerException- ifthatis null
-
zipWith
<U,R> Traversable<R> zipWith(java.lang.Iterable<? extends U> that, java.util.function.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:
java.lang.NullPointerException- ifthatormapperis null
-
zipWithIndex
Traversable<Tuple2<T,java.lang.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
<U> Traversable<U> zipWithIndex(java.util.function.BiFunction<? super T,? super java.lang.Integer,? extends U> mapper)
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:
java.lang.NullPointerException- ifmapperis null
-
-