Interface Traversable<T>
-
- Type Parameters:
T
- Component type
- All Known Subinterfaces:
IndexedSeq<T>
,Iterator<T>
,LinearSeq<T>
,Map<K,V>
,Multimap<K,V>
,Seq<T>
,Set<T>
,SortedMap<K,V>
,SortedMultimap<K,V>
,SortedSet<T>
- All Known Implementing Classes:
Array
,BitSet
,CharSeq
,HashMap
,HashMultimap
,HashSet
,LinkedHashMap
,LinkedHashMultimap
,LinkedHashSet
,List
,List.Cons
,List.Nil
,PriorityQueue
,Queue
,Stream
,Stream.Cons
,Stream.Empty
,Tree
,Tree.Empty
,Tree.Node
,TreeMap
,TreeMultimap
,TreeSet
,Vector
public interface Traversable<T> extends Iterable<T>, 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)
fold(Object, BiFunction)
foldLeft(Object, BiFunction)
foldRight(Object, BiFunction)
mkString()
mkString(CharSequence)
mkString(CharSequence, CharSequence, CharSequence)
reduce(BiFunction)
reduceOption(BiFunction)
reduceLeft(BiFunction)
reduceLeftOption(BiFunction)
reduceRight(BiFunction)
reduceRightOption(BiFunction)
drop(int)
dropRight(int)
dropUntil(Predicate)
dropWhile(Predicate)
filter(Predicate)
filterNot(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 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 givenpartialFunction
by mapping the elements to typeR
.default boolean
containsAll(java.lang.Iterable<? extends T> elements)
Tests if this Traversable contains all given elements.default int
count(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.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) 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 boolean
existsUnique(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 Traversable<T>
filterNot(java.util.function.Predicate<? super T> predicate)
Returns a new traversable consisting of all elements which do not 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 T
fold(T zero, java.util.function.BiFunction<? super T,? super T,? extends T> combine)
Folds this elements using the given associative binary operator, starting withzero
and successively callingcombine
.default <U> U
foldLeft(U zero, java.util.function.BiFunction<? super U,? super T,? extends U> combine)
Folds this elements from the left, starting withzero
and successively callingcombine
.<U> U
foldRight(U zero, java.util.function.BiFunction<? super T,? super U,? extends U> combine)
Folds this elements from the right, starting withzero
and successively callingcombine
.default void
forEachWithIndex(java.util.function.ObjIntConsumer<? super T> action)
Performs an action on each element.default T
get()
Gets the first value in iteration order if thisTraversable
is 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 thisTraversable
into fixed size blocks.boolean
hasDefiniteSize()
Checks if this Traversable is known to have a finite size.int
hashCode()
Returns the hash code of this collection.T
head()
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 boolean
isDistinct()
Checks if this Traversable may consist of distinct elements only.default boolean
isEmpty()
Checks if this Traversable is empty.default boolean
isOrdered()
Checks if this Traversable is ordereddefault boolean
isSequential()
Checks if the elements of this Traversable appear in encounter order.default boolean
isSingleValued()
Each of Vavr's collections may contain more than one element.boolean
isTraversableAgain()
Checks if this Traversable can be repeatedly traversed.default Iterator<T>
iterator()
An iterator by means of head() and tail().T
last()
Dual of head(), returning the last element.default Option<T>
lastOption()
Dual of headOption(), returning the last element asOption
.int
length()
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 thisTraversable
to 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 CharSeq
mkCharSeq()
Joins the elements of this by concatenating their string representations.default CharSeq
mkCharSeq(java.lang.CharSequence delimiter)
Joins the string representations of this elements using a specific delimiter.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.default java.lang.String
mkString()
Joins the elements of this by concatenating their string representations.default java.lang.String
mkString(java.lang.CharSequence delimiter)
Joins the string representations of this elements using a specific delimiter.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.static <T> Traversable<T>
narrow(Traversable<? extends T> traversable)
Narrows a widenedTraversable<? extends T>
toTraversable<T>
by performing a type-safe cast.default boolean
nonEmpty()
Checks, thisTraversable
is not empty.Traversable<T>
orElse(java.lang.Iterable<? extends T> other)
Returns thisTraversable
if it is nonempty, otherwise return the alternative.Traversable<T>
orElse(java.util.function.Supplier<? extends java.lang.Iterable<? extends T>> supplier)
Returns thisTraversable
if 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 thisTraversable
by splitting this elements in two in distinct traversables according to a predicate.Traversable<T>
peek(java.util.function.Consumer<? super T> action)
Performs the givenaction
on the first element if this is an eager implementation.default java.lang.Number
product()
Calculates the product of this elements.default T
reduce(java.util.function.BiFunction<? super T,? super T,? extends T> op)
Accumulates the elements of this Traversable by successively calling the given operationop
.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 operationop
from the left.default Option<T>
reduceLeftOption(java.util.function.BiFunction<? super T,? super T,? extends T> op)
Accumulates the elements of this Traversable by successively calling the given operationop
from the left.default Option<T>
reduceOption(java.util.function.BiFunction<? super T,? super T,? extends T> op)
Accumulates the elements of this Traversable by successively calling the given operationop
.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 operationop
from the right.default Option<T>
reduceRightOption(java.util.function.BiFunction<? super T,? super T,? extends T> op)
Accumulates the elements of this Traversable by successively calling the given operationop
from the right.default Traversable<T>
reject(java.util.function.Predicate<? super T> predicate)
Deprecated.Please usefilterNot(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 T
single()
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 int
size()
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 specificsize
and step size 1 over thisTraversable
by callingsliding(int, int)
.Iterator<? extends Traversable<T>>
sliding(int size, int step)
Slides a window of a specificsize
andstep
size 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 givenpredicate
and the second element is the remainder.default java.util.Spliterator<T>
spliterator()
default java.lang.Number
sum()
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)
Returns a traversable formed from this traversable and another Iterable collection by mapping elements.-
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
traversable
instance 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
- ifgetKey
is 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 typeT
is 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() // throws
DoubleStream.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 givenpartialFunction
by 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)
Traversable
is ordered (i.e. extendsOrdered
, the caller ofcollect
has 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
Traversable
instance containing elements of typeR
- Throws:
java.lang.NullPointerException
- ifpartialFunction
is 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
- ifelements
is 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
- ifpredicate
is null.
-
distinct
Traversable<T> distinct()
Returns a new version of this which contains no duplicates. Elements are compared usingequals
.- Returns:
- a new
Traversable
containing 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
Traversable
containing this elements without duplicates - Throws:
java.lang.NullPointerException
- ifcomparator
is 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
Traversable
containing this elements without duplicates - Throws:
java.lang.NullPointerException
- ifkeyExtractor
is 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
- ifpredicate
is 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
- ifpredicate
is 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
- ifpredicate
is 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
- ifpredicate
is null
-
filterNot
default Traversable<T> filterNot(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
- ifpredicate
is null
-
reject
@Deprecated default Traversable<T> reject(java.util.function.Predicate<? super T> predicate)
Deprecated.Please usefilterNot(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
- ifpredicate
is 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
- ifpredicate
is 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
- ifpredicate
is 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.
-
fold
default T fold(T zero, java.util.function.BiFunction<? super T,? super T,? extends T> combine)
Folds this elements using the given associative binary operator, starting withzero
and successively callingcombine
. The order in which the elements are combined is non-deterministic.The methods
fold
,foldLeft
andfoldRight
differ in how the elements are combined:foldLeft(Object, BiFunction)
associates to the leftfoldRight(Object, BiFunction)
associates to the right-
fold
takes an associative combine operation because the traversal of elements is unordered/non-deterministic. The associativity guarantees that in each case the result will be the same, it does not matter in which order the elements are combined. Generally binary operators aren't associative, i.e. the result may differ if elements are combined in a different order.We say that this Traversable and the associative combine operation form a Monoid.
// = 6 Set(1, 2, 3).fold(0, (a, b) -> a + b);
-
foldLeft
default <U> U foldLeft(U zero, java.util.function.BiFunction<? super U,? super T,? extends U> combine)
Folds this elements from the left, starting withzero
and 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> combine)
Folds this elements from the right, starting withzero
and 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 toIterable.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 intermediateTuple2
instances are created and no boxing of int values takes place.Please note that subsequent calls to
forEachWithIndex
might lead to different iteration orders, depending on the underlyingTraversable
implementation.Please also note that
forEachWithIndex
might loop infinitely if theTraversable
is lazily evaluated, likeStream
.- Parameters:
action
- AObjIntConsumer
- Throws:
java.lang.NullPointerException
- ifaction
is null
-
get
default T get()
Gets the first value in iteration order if thisTraversable
is 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
- ifclassifier
is null.- See Also:
arrangeBy(Function)
-
grouped
Iterator<? extends Traversable<T>> grouped(int size)
Groups thisTraversable
into fixed size blocks.Let length be the length of this Iterable. Then grouped is defined as follows:
- If
this.isEmpty()
, the resultingIterator
is empty. - If
size <= length
, the resultingIterator
will containlength / size
blocks of sizesize
and maybe a non-empty block of sizelength % size
, if there are remaining elements. - If
size > length
, the resultingIterator
will contain one block of sizelength
.
[].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
- ifsize
is 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)
orNone
if 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)
orNone
if 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:
isSingleValued
in 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)
orNone
if 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 thisTraversable
to 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 orNone
if 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 orNone
if this is empty- Throws:
java.lang.NullPointerException
- ifcomparator
is 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
- iff
is 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:
List.empty().min() // = None List.of(1, 2, 3).min() // = Some(1) List.of("a", "b", "c").min() // = Some("a") List.of(1.0, Double.NaN).min() // = NaN List.of(1, "a").min() // throws
Double
andFloat
: The minimum is defined to beNaN
if this containsNaN
. According to the natural orderNaN
would be the maximum element instead.- Returns:
Some(minimum)
of this elements orNone
if 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 orNone
if this is empty- Throws:
java.lang.NullPointerException
- ifcomparator
is 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
- iff
is 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, thisTraversable
is 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 thisTraversable
if it is nonempty, otherwise return the alternative.- Parameters:
other
- An alternativeTraversable
- Returns:
- this
Traversable
if it is nonempty, otherwise return the alternative.
-
orElse
Traversable<T> orElse(java.util.function.Supplier<? extends java.lang.Iterable<? extends T>> supplier)
Returns thisTraversable
if it is nonempty, otherwise return the result of evaluating supplier.- Parameters:
supplier
- An alternativeTraversable
supplier- Returns:
- this
Traversable
if 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 thisTraversable
by 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
Traversable
contains all elements that satisfy the givenpredicate
, the secondTraversable
contains 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:Value
Performs the givenaction
on the first element if this is an eager implementation. Performs the givenaction
on 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
,BigInteger
andBigDecimal
.Examples:
List.empty().product() // = 1 List.of(1, 2, 3).product() // = 6L List.of(0.1, 0.2, 0.3).product() // = 0.006 List.of("apple", "pear").product() // throws
fold(Object, BiFunction)
, a way to do a type-safe multiplication of elements.- Returns:
- a
Number
representing the sum of this elements - Throws:
java.lang.UnsupportedOperationException
- if this elements are not numeric
-
reduce
default T reduce(java.util.function.BiFunction<? super T,? super T,? extends T> op)
Accumulates the elements of this Traversable by successively calling the given operationop
. The order of element iteration is undetermined.
-
reduceOption
default Option<T> reduceOption(java.util.function.BiFunction<? super T,? super T,? extends T> op)
Accumulates the elements of this Traversable by successively calling the given operationop
. The order of element iteration is undetermined.- Specified by:
reduceOption
in interfaceFoldable<T>
- Parameters:
op
- A BiFunction of type T- Returns:
- Some of reduced value or None if the Foldable is empty.
- Throws:
java.lang.NullPointerException
- ifop
is null
-
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 operationop
from the left.- Specified by:
reduceLeft
in interfaceFoldable<T>
- Parameters:
op
- A BiFunction of type T- Returns:
- the reduced value.
- Throws:
java.util.NoSuchElementException
- if this is emptyjava.lang.NullPointerException
- ifop
is null
-
reduceLeftOption
default Option<T> reduceLeftOption(java.util.function.BiFunction<? super T,? super T,? extends T> op)
Accumulates the elements of this Traversable by successively calling the given operationop
from the left.
Shortcut forisEmpty() ? Option.none() : Option.some(reduceLeft(op))
.- Specified by:
reduceLeftOption
in interfaceFoldable<T>
- Parameters:
op
- A BiFunction of type T- Returns:
- Some of reduced value or None if the Traversable is empty.
- Throws:
java.lang.NullPointerException
- ifop
is 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 operationop
from the right.- Specified by:
reduceRight
in interfaceFoldable<T>
- Parameters:
op
- An operation of type T- Returns:
- the reduced value.
- Throws:
java.util.NoSuchElementException
- if this is emptyjava.lang.NullPointerException
- ifop
is null
-
reduceRightOption
default Option<T> reduceRightOption(java.util.function.BiFunction<? super T,? super T,? extends T> op)
Accumulates the elements of this Traversable by successively calling the given operationop
from the right.
Shortcut forisEmpty() ? Option.none() : Option.some(reduceRight(op))
.- Specified by:
reduceRightOption
in interfaceFoldable<T>
- Parameters:
op
- An operation of type T- Returns:
- Some of reduced value or None.
- Throws:
java.lang.NullPointerException
- ifop
is 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
- ifelements
is 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
- ifoperation
is 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
- ifoperation
is 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
- ifoperation
is 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)
orNone
if 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 thisTraversable
will be in the same window only ifclassifier
returns 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
- ifclassifier
is null.
-
sliding
Iterator<? extends Traversable<T>> sliding(int size)
Slides a window of a specificsize
and step size 1 over thisTraversable
by 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
- ifsize
is negative or zero
-
sliding
Iterator<? extends Traversable<T>> sliding(int size, int step)
Slides a window of a specificsize
andstep
size 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
- ifsize
orstep
are 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 givenpredicate
and the second element is the remainder.- Parameters:
predicate
- A predicate.- Returns:
- a
Tuple
containing the longest prefix of elements that satisfy p and the remainder. - Throws:
java.lang.NullPointerException
- ifpredicate
is null
-
spliterator
default java.util.Spliterator<T> spliterator()
- Specified by:
spliterator
in interfacejava.lang.Iterable<T>
- Specified by:
spliterator
in interfaceValue<T>
-
sum
default java.lang.Number sum()
Calculates the sum of this elements. Supported component types areByte
,Double
,Float
,Integer
,Long
,Short
,BigInteger
andBigDecimal
.Examples:
List.empty().sum() // = 0 List.of(1, 2, 3).sum() // = 6L List.of(0.1, 0.2, 0.3).sum() // = 0.6 List.of("apple", "pear").sum() // throws
fold(Object, BiFunction)
, a way to do a type-safe summation of elements.- Returns:
- a
Number
representing 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)
orNone
if 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 < 0
orn > length()
.In the case of
n < 0
the 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 < 0
orn > length()
.In the case of
n < 0
the 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
- ifpredicate
is 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
- ifpredicate
is 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
- ifunzipper
is 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
- ifunzipper
is 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
that
iterable.- 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
that
iterable. - Throws:
java.lang.NullPointerException
- ifthat
is 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
that
iterable.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
- ifthat
is 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
that
iterable.- 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
that
iterable. - Throws:
java.lang.NullPointerException
- ifthat
ormapper
is 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)
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
that
iterable.- Type Parameters:
U
- The type of the mapped elements.- Parameters:
mapper
- a mapper.- Returns:
- a new traversable containing mapped elements of this traversable and
that
iterable. - Throws:
java.lang.NullPointerException
- ifmapper
is null
-
-