Interface Tree<T>
-
- Type Parameters:
T- component type of this Tree
- All Superinterfaces:
Foldable<T>,java.lang.Iterable<T>,java.io.Serializable,Traversable<T>,Value<T>
- All Known Implementing Classes:
Tree.Empty,Tree.Node
public interface Tree<T> extends Traversable<T>, java.io.Serializable
A general Tree interface.
-
-
Nested Class Summary
Nested Classes Modifier and Type Interface Description static classTree.Empty<T>The empty tree.static classTree.Node<T>Represents a tree node.static classTree.OrderTree traversal order.
-
Field Summary
Fields Modifier and Type Field Description static longserialVersionUIDThe serial version UID for serialization.
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Default Methods Modifier and Type Method Description default intbranchCount()Counts the number of branches of this tree.static <T,ID>
List<Tree.Node<T>>build(@NonNull java.lang.Iterable<? extends T> source, @NonNull java.util.function.Function<? super T,? extends ID> idMapper, @NonNull java.util.function.Function<? super T,? extends ID> parentMapper)Build aListwith roots ofTreefrom flat source.default <R> Tree<R>collect(@NonNull PartialFunction<? super T,? extends R> partialFunction)Applies aPartialFunctionto all elements that are defined for it and collects the results.static <T> java.util.stream.Collector<T,java.util.ArrayList<T>,Tree<T>>collector()Returns aCollectorwhich may be used in conjunction withStream.collect(java.util.stream.Collector)to obtain aTree.default Seq<T>distinct()Returns a newTraversablecontaining the elements of this instance with all duplicates removed.default Seq<T>distinctBy(@NonNull java.util.Comparator<? super T> comparator)Returns a newTraversablecontaining the elements of this instance without duplicates, as determined by the givencomparator.default <U> Seq<T>distinctBy(@NonNull java.util.function.Function<? super T,? extends U> keyExtractor)Returns a newTraversablecontaining the elements of this instance without duplicates, based on keys extracted from elements usingkeyExtractor.java.lang.Stringdraw()Creates a neat 2-dimensional drawing of a tree.default Seq<T>drop(int n)Returns a newTraversablewithout the firstnelements, or an empty instance if this contains fewer thannelements.default Seq<T>dropRight(int n)Returns a newTraversablewithout the lastnelements, or an empty instance if this contains fewer thannelements.default Seq<T>dropUntil(@NonNull java.util.function.Predicate<? super T> predicate)Returns a newTraversablestarting from the first element that satisfies the givenpredicate, dropping all preceding elements.default Seq<T>dropWhile(@NonNull java.util.function.Predicate<? super T> predicate)Returns a newTraversablestarting from the first element that does not satisfy the givenpredicate, dropping all preceding elements.static <T> Tree.Empty<T>empty()Returns the singleton empty tree.booleanequals(java.lang.Object o)Determines whether this collection is equal to the given object.static <T> Tree<T>fill(int n, @NonNull java.util.function.Supplier<? extends T> s)Returns a Tree containingnvalues supplied by a given Suppliers.static <T> Tree<T>fill(int n, T element)Returns a Tree containingntimes the givenelementdefault Seq<T>filter(@NonNull java.util.function.Predicate<? super T> predicate)Returns a new traversable containing only the elements that satisfy the given predicate.default <U> Tree<U>flatMap(@NonNull java.util.function.Function<? super T,? extends java.lang.Iterable<? extends U>> mapper)Transforms each element of this Traversable into anIterableof elements and flattens the resulting iterables into a single Traversable.default <U> UfoldRight(U zero, @NonNull java.util.function.BiFunction<? super T,? super U,? extends U> f)Folds the elements of this structure from the right, starting with the givenzerovalue and successively applying thecombinefunction to each element.List<Tree.Node<T>>getChildren()Returns the children of this tree.TgetValue()Gets the value of this tree.default <C> Map<C,Seq<T>>groupBy(@NonNull java.util.function.Function<? super T,? extends C> classifier)Groups elements of thisTraversablebased on a classifier function.default Iterator<Seq<T>>grouped(int size)Splits thisTraversableinto consecutive blocks of the given size.default booleanhasDefiniteSize()Indicates whether thisTraversablehas a known finite size.inthashCode()Returns the hash code of this collection.default Thead()Returns the first element of this non-emptyTraversable.default Seq<T>init()Returns all elements of this Traversable except the last one.default Option<Seq<T>>initOption()Returns all elements of this Traversable except the last one, wrapped in anOption.default booleanisAsync()ATreeis computed synchronously.default booleanisBranch()Checks if this Tree is a branch.default booleanisDistinct()Indicates whether this Traversable may contain only distinct elements.default booleanisLazy()ATreeis computed eagerly.booleanisLeaf()Checks if this Tree is a leaf.default booleanisSequential()Indicates whether the elements of this Traversable appear in encounter (insertion) order.default booleanisTraversableAgain()Checks if this Traversable can be traversed multiple times without side effects.default @NonNull Iterator<T>iterator()Returns an iterator over the elements of this Traversable, implemented viaTraversable.head()andTraversable.tail().default Iterator<T>iterator(Tree.Order order)Traverses this tree values in a specificTree.Order.default intleafCount()Counts the number of leaves of this tree.default <U> Tree<U>map(@NonNull java.util.function.Function<? super T,? extends U> mapper)Transforms the elements of this Traversable to a new type, preserving order if defined.default <U> Tree<U>mapTo(U value)Maps the underlying value to another fixed value.default Tree<java.lang.Void>mapToVoid()Maps the underlying value to Voidstatic <T> Tree<T>narrow(Tree<? extends T> tree)Narrows a widenedTree<? extends T>toTree<T>by performing a type-safe cast.default intnodeCount()Counts the number of nodes (i.e.static <T> Tree.Node<T>of(T value)Returns a new Node containing the given value and having no children.static <T> Tree<T>of(T @NonNull ... values)Creates a Tree of the given elements.static <T> Tree.Node<T>of(T value, @NonNull Tree.Node<T> @NonNull ... children)Returns a new Node containing the given value and having the given children.static <T> Tree.Node<T>of(T value, @NonNull java.lang.Iterable<Tree.Node<T>> children)Returns a new Node containing the given value and having the given children.static <T> Tree<T>ofAll(@NonNull java.lang.Iterable<? extends T> iterable)Creates a Tree of the given elements.static <T> Tree<T>ofAll(@NonNull java.util.stream.Stream<? extends T> javaStream)Creates a Tree that contains the elements of the givenStream.default Tree<T>orElse(@NonNull java.lang.Iterable<? extends T> other)Returns thisTraversableif it is non-empty; otherwise, returns the given alternative.default Tree<T>orElse(@NonNull java.util.function.Supplier<? extends java.lang.Iterable<? extends T>> supplier)Returns thisTraversableif it is non-empty; otherwise, returns the result of evaluating the given supplier.default Tuple2<Seq<T>,Seq<T>>partition(@NonNull java.util.function.Predicate<? super T> predicate)Splits thisTraversableinto two partitions according to a predicate.default Tree<T>peek(@NonNull java.util.function.Consumer<? super T> action)Performs the givenactionon the first element if this is an eager implementation.static <T> Tree.Node<T>recurse(T seed, @NonNull java.util.function.Function<? super T,? extends java.lang.Iterable<? extends T>> descend)Recursively builds a non-emptyTree, starting with the givenseedvalue and proceeding in depth-first order.default Seq<T>reject(@NonNull java.util.function.Predicate<? super T> predicate)Returns a new traversable containing only the elements that do not satisfy the given predicate.default Tree<T>replace(T currentElement, T newElement)Replaces the first occurrence ofcurrentElementwithnewElement, if it exists.default Tree<T>replaceAll(T currentElement, T newElement)Replaces all occurrences ofcurrentElementwithnewElement.default Seq<T>retainAll(@NonNull java.lang.Iterable<? extends T> elements)Retains only the elements from this Traversable that are contained in the givenelements.default Seq<T>scan(T zero, @NonNull java.util.function.BiFunction<? super T,? super T,? extends T> operation)Computes a prefix scan of the elements of this Traversable.default <U> Seq<U>scanLeft(U zero, @NonNull java.util.function.BiFunction<? super U,? super T,? extends U> operation)Produces a collection containing cumulative results of applying the operator from left to right.default <U> Seq<U>scanRight(U zero, @NonNull java.util.function.BiFunction<? super T,? super U,? extends U> operation)Produces a collection containing cumulative results of applying the operator from right to left.default Iterator<Seq<T>>slideBy(@NonNull java.util.function.Function<? super T,?> classifier)Partitions thisTraversableinto consecutive non-overlapping windows according to a classification function.default Iterator<Seq<T>>sliding(int size)Slides a window of a givensizeover thisTraversablewith a step size of 1.default Iterator<Seq<T>>sliding(int size, int step)Slides a window of a specificsizewith a givenstepover thisTraversable.default Tuple2<Seq<T>,Seq<T>>span(@NonNull java.util.function.Predicate<? super T> predicate)Splits thisTraversableinto a prefix and remainder according to the givenpredicate.default java.lang.StringstringPrefix()Returns the name of this Value type, which is used by toString().static <T> Tree<T>tabulate(int n, @NonNull java.util.function.Function<? super java.lang.Integer,? extends T> f)Returns a Tree containingnvalues of a given Functionfover a range of integer values from 0 ton - 1.default Seq<T>tail()Returns a newTraversablewithout its first element.default Option<Seq<T>>tailOption()Returns a newTraversablewithout its first element as anOption.default Seq<T>take(int n)Returns the firstnelements of thisTraversable, or all elements ifnexceeds the length.default Seq<T>takeRight(int n)Returns the lastnelements of thisTraversable, or all elements ifnexceeds the length.default Seq<T>takeUntil(@NonNull java.util.function.Predicate<? super T> predicate)Takes elements from thisTraversableuntil the given predicate holds for an element.default Seq<T>takeWhile(@NonNull java.util.function.Predicate<? super T> predicate)Takes elements from thisTraversablewhile the given predicate holds.java.lang.StringtoLispString()Creates a Lisp-like representation of thisTree.java.lang.StringtoString()Clarifies that values have a proper toString() method implemented.default <U> Utransform(@NonNull java.util.function.Function<? super Tree<T>,? extends U> f)Transforms thisTree.default Seq<Tree.Node<T>>traverse()Traverses this tree inTree.Order.PRE_ORDER.default Seq<Tree.Node<T>>traverse(@NonNull Tree.Order order)Traverses this tree in a specific order.default <T1,T2>
Tuple2<Tree<T1>,Tree<T2>>unzip(@NonNull java.util.function.Function<? super T,Tuple2<? extends T1,? extends T2>> unzipper)Unzips the elements of thisTraversableby mapping each element to a pair and splitting them into two separateTraversablecollections.default <T1,T2,T3>
Tuple3<Tree<T1>,Tree<T2>,Tree<T3>>unzip3(@NonNull java.util.function.Function<? super T,Tuple3<? extends T1,? extends T2,? extends T3>> unzipper)Unzips the elements of thisTraversableby mapping each element to a triple and splitting them into three separateTraversablecollections.default Seq<T>values()Traverses this tree values inTree.Order.PRE_ORDER.default Seq<T>values(@NonNull Tree.Order order)Traverses this tree values in a specific order.default <U> Tree<Tuple2<T,U>>zip(@NonNull java.lang.Iterable<? extends U> that)Returns aTraversableformed by pairing elements of thisTraversablewith elements of anotherIterable.default <U> Tree<Tuple2<T,U>>zipAll(@NonNull java.lang.Iterable<? extends U> that, T thisElem, U thatElem)Returns aTraversableformed by pairing elements of thisTraversablewith elements of anotherIterable, filling in placeholder elements when one collection is shorter than the other.default <U,R>
Tree<R>zipWith(@NonNull java.lang.Iterable<? extends U> that, java.util.function.BiFunction<? super T,? super U,? extends R> mapper)Returns aTraversableby combining elements of thisTraversablewith elements of anotherIterableusing a mapping function.default Tree<Tuple2<T,java.lang.Integer>>zipWithIndex()Zips thisTraversablewith its indices, starting at 0.default <U> Tree<U>zipWithIndex(@NonNull java.util.function.BiFunction<? super T,? super java.lang.Integer,? extends U> mapper)Zips thisTraversablewith its indices and maps the resulting pairs using the provided mapper.-
Methods inherited from interface io.vavr.collection.Foldable
fold, reduce, reduceOption
-
Methods inherited from interface io.vavr.collection.Traversable
arrangeBy, average, containsAll, count, existsUnique, find, findLast, foldLeft, forEachWithIndex, get, headOption, isEmpty, isOrdered, isSingleValued, last, lastOption, length, max, maxBy, maxBy, min, minBy, minBy, mkCharSeq, mkCharSeq, mkCharSeq, mkString, mkString, mkString, nonEmpty, product, reduceLeft, reduceLeftOption, reduceRight, reduceRightOption, single, singleOption, size, spliterator, sum
-
Methods inherited from interface io.vavr.Value
collect, collect, contains, corresponds, eq, exists, forAll, forEach, getOrElse, getOrElse, getOrElseThrow, getOrElseTry, getOrNull, out, out, stderr, stdout, 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, toTree, toTree, toTry, toTry, toValid, toValid, toValidation, toValidation, toVector
-
-
-
-
Field Detail
-
serialVersionUID
static final long serialVersionUID
The serial version UID for serialization.- See Also:
- Constant Field Values
-
-
Method Detail
-
collector
static <T> java.util.stream.Collector<T,java.util.ArrayList<T>,Tree<T>> collector()
Returns aCollectorwhich may be used in conjunction withStream.collect(java.util.stream.Collector)to obtain aTree.- Type Parameters:
T- Component type of the Tree.- Returns:
- A io.vavr.collection.Tree Collector.
-
empty
static <T> Tree.Empty<T> empty()
Returns the singleton empty tree.- Type Parameters:
T- Type of tree values.- Returns:
- The empty tree.
-
narrow
static <T> Tree<T> narrow(Tree<? extends T> tree)
Narrows a widenedTree<? extends T>toTree<T>by performing a type-safe cast. This is eligible because immutable/read-only collections are covariant.- Type Parameters:
T- Component type of theTree.- Parameters:
tree- AnTree.- Returns:
- the given
treeinstance as narrowed typeTree<T>.
-
of
static <T> Tree.Node<T> of(T value)
Returns a new Node containing the given value and having no children.- Type Parameters:
T- Value type- Parameters:
value- A value- Returns:
- A new Node instance.
-
of
@SafeVarargs static <T> Tree.Node<T> of(T value, @NonNull Tree.Node<T> @NonNull ... children)
Returns a new Node containing the given value and having the given children.- Type Parameters:
T- Value type- Parameters:
value- A valuechildren- The child nodes, possibly empty- Returns:
- A new Node instance.
-
of
static <T> Tree.Node<T> of(T value, @NonNull java.lang.Iterable<Tree.Node<T>> children)
Returns a new Node containing the given value and having the given children.- Type Parameters:
T- Value type- Parameters:
value- A valuechildren- The child nodes, possibly empty- Returns:
- A new Node instance.
-
of
@SafeVarargs static <T> Tree<T> of(T @NonNull ... values)
Creates a Tree of the given elements.- Type Parameters:
T- Component type of the List.- Parameters:
values- Zero or more values.- Returns:
- A Tree containing the given values.
- Throws:
java.lang.NullPointerException- ifvaluesis null
-
ofAll
static <T> Tree<T> ofAll(@NonNull java.lang.Iterable<? extends T> iterable)
Creates a Tree of the given elements.If the given iterable is a tree, it is returned as result. if the iteration order of the elements is stable.
- Type Parameters:
T- Component type of the List.- Parameters:
iterable- An Iterable of elements.- Returns:
- A list containing the given elements in the same order.
- Throws:
java.lang.NullPointerException- ifelementsis null
-
ofAll
static <T> Tree<T> ofAll(@NonNull java.util.stream.Stream<? extends T> javaStream)
Creates a Tree that contains the elements of the givenStream.- Type Parameters:
T- Component type of the Stream.- Parameters:
javaStream- AStream- Returns:
- A Tree containing the given elements in the same order.
-
tabulate
static <T> Tree<T> tabulate(int n, @NonNull java.util.function.Function<? super java.lang.Integer,? extends T> f)
Returns a Tree containingnvalues of a given Functionfover a range of integer values from 0 ton - 1.- Type Parameters:
T- Component type of the Tree- Parameters:
n- The number of elements in the Treef- The Function computing element values- Returns:
- A Tree consisting of elements
f(0),f(1), ..., f(n - 1) - Throws:
java.lang.NullPointerException- iffis null
-
fill
static <T> Tree<T> fill(int n, @NonNull java.util.function.Supplier<? extends T> s)
Returns a Tree containingnvalues supplied by a given Suppliers.- Type Parameters:
T- Component type of the Tree- Parameters:
n- The number of elements in the Trees- The Supplier computing element values- Returns:
- A Tree of size
n, where each element contains the result supplied bys. - Throws:
java.lang.NullPointerException- ifsis null
-
fill
static <T> Tree<T> fill(int n, T element)
Returns a Tree containingntimes the givenelement- Type Parameters:
T- Component type of the Tree- Parameters:
n- The number of elements in the Treeelement- The element- Returns:
- A Tree of size
n, where each element is the givenelement.
-
recurse
static <T> Tree.Node<T> recurse(T seed, @NonNull java.util.function.Function<? super T,? extends java.lang.Iterable<? extends T>> descend)
Recursively builds a non-emptyTree, starting with the givenseedvalue and proceeding in depth-first order.The children of a node are created by
- applying the
descendfunction to the node value - calling this method recursively by using each derived child value as new seed (in iteration order).
Example:
// = (1 (2 4 5) 3) Tree.recurse(1, i -> (i == 1) ? List.of(2, 3) : (i == 2) ? List.(4, 5) : List.empty() ).toLispString();- Type Parameters:
T- Value type- Parameters:
seed- The start value for the Treedescend- A function to calculate the child values- Returns:
- a new, non-empty
Treeinstance - Throws:
java.lang.NullPointerException- ifdescendis null
- applying the
-
build
static <T,ID> List<Tree.Node<T>> build(@NonNull java.lang.Iterable<? extends T> source, @NonNull java.util.function.Function<? super T,? extends ID> idMapper, @NonNull java.util.function.Function<? super T,? extends ID> parentMapper)
Build aListwith roots ofTreefrom flat source.parentMappermust returnnullfor root element.// = [(1, null, "I"), (2, 1, "II"), (3, 1, "III"), (4, 2, "IV"), (5, 2, "V")] List<MenuItem> items = ...; // MenuItem(id, parentId, label) // I // / \ // II III // /\ // IV V Tree<MenuItem> menu = Tree.build(items, MenuItem::getId, MenuItem::getParentId);- Type Parameters:
T- Value typeID- Id type- Parameters:
source- Flat sourceidMapper- A mapper from source item to unique identifier of that itemparentMapper- A mapper from source item to unique identifier of parent item. Need return null for root items- Returns:
- a new, maybe empty
Listinstance with non-emptyTreeinstances - Throws:
java.lang.NullPointerException- ifsource,idMapperorparentMapperis null
-
collect
default <R> Tree<R> collect(@NonNull PartialFunction<? super T,? extends R> partialFunction)
Description copied from interface:TraversableApplies aPartialFunctionto all elements that are defined for it and collects the results.For each element in iteration order, the function is first tested:
IfpartialFunction.isDefinedAt(element)true, the element is mapped to typeR:R newElement = partialFunction.apply(element)Note: If this
Traversableis ordered (i.e., extendsOrdered), the caller must ensure that the resulting elements are comparable (i.e., implementComparable).- Specified by:
collectin interfaceTraversable<T>- Type Parameters:
R- the type of elements in the resultingTraversable- Parameters:
partialFunction- a function that may not be defined for all elements of this traversable- Returns:
- a new
Traversablecontaining the results of applying the partial function
-
getValue
T getValue()
Gets the value of this tree.- Returns:
- The value of this tree.
- Throws:
java.lang.UnsupportedOperationException- if this tree is empty
-
getChildren
List<Tree.Node<T>> getChildren()
Returns the children of this tree.- Returns:
- the tree's children
-
isLeaf
boolean isLeaf()
Checks if this Tree is a leaf. A tree is a leaf if it is a Node with no children. Because the empty tree is no Node, it is not a leaf by definition.- Returns:
- true if this tree is a leaf, false otherwise.
-
isBranch
default boolean isBranch()
Checks if this Tree is a branch. A Tree is a branch if it is a Node which has children. Because the empty tree is not a Node, it is not a branch by definition.- Returns:
- true if this tree is a branch, false otherwise.
-
isAsync
default boolean isAsync()
ATreeis computed synchronously.
-
isDistinct
default boolean isDistinct()
Description copied from interface:TraversableIndicates whether this Traversable may contain only distinct elements.- Specified by:
isDistinctin interfaceTraversable<T>- Returns:
trueif this Traversable may contain only distinct elements,falseotherwise
-
isLazy
default boolean isLazy()
ATreeis computed eagerly.
-
isSequential
default boolean isSequential()
Description copied from interface:TraversableIndicates whether the elements of this Traversable appear in encounter (insertion) order.- Specified by:
isSequentialin interfaceTraversable<T>- Returns:
trueif insertion order is preserved,falseotherwise
-
iterator
default Iterator<T> iterator(Tree.Order order)
Traverses this tree values in a specificTree.Order.- Parameters:
order- A traversal order- Returns:
- A new Iterator
-
toLispString
java.lang.String toLispString()
Creates a Lisp-like representation of thisTree.- Returns:
- This
Treeas Lisp-string, i.e. represented as list of lists.
-
transform
default <U> U transform(@NonNull java.util.function.Function<? super Tree<T>,? extends U> f)
Transforms thisTree.- Type Parameters:
U- Type of transformation result- Parameters:
f- A transformation- Returns:
- An instance of type
U - Throws:
java.lang.NullPointerException- iffis null
-
traverse
default Seq<Tree.Node<T>> traverse()
Traverses this tree inTree.Order.PRE_ORDER.- Returns:
- A sequence of nodes.
-
traverse
default Seq<Tree.Node<T>> traverse(@NonNull Tree.Order order)
Traverses this tree in a specific order.- Parameters:
order- the tree traversal order- Returns:
- A sequence of nodes.
- Throws:
java.lang.NullPointerException- if order is null
-
values
default Seq<T> values()
Traverses this tree values inTree.Order.PRE_ORDER. Syntactic sugar fortraverse().map(Node::getValue).- Returns:
- A sequence of the tree values.
-
values
default Seq<T> values(@NonNull Tree.Order order)
Traverses this tree values in a specific order. Syntactic sugar fortraverse(order).map(Node::getValue).- Parameters:
order- the tree traversal order- Returns:
- A sequence of the tree values.
- Throws:
java.lang.NullPointerException- if order is null
-
branchCount
default int branchCount()
Counts the number of branches of this tree. The empty tree and a leaf have no branches.- Returns:
- The number of branches of this tree.
-
leafCount
default int leafCount()
Counts the number of leaves of this tree. The empty tree has no leaves.- Returns:
- The number of leaves of this tree.
-
nodeCount
default int nodeCount()
Counts the number of nodes (i.e. branches and leaves) of this tree. The empty tree has no nodes.- Returns:
- The number of nodes of this tree.
-
distinct
default Seq<T> distinct()
Description copied from interface:TraversableReturns a newTraversablecontaining the elements of this instance with all duplicates removed. Element equality is determined usingequals.- Specified by:
distinctin interfaceTraversable<T>- Returns:
- a new
Traversablewithout duplicate elements
-
distinctBy
default Seq<T> distinctBy(@NonNull java.util.Comparator<? super T> comparator)
Description copied from interface:TraversableReturns a newTraversablecontaining the elements of this instance without duplicates, as determined by the givencomparator.- Specified by:
distinctByin interfaceTraversable<T>- Parameters:
comparator- a comparator used to determine equality of elements- Returns:
- a new
Traversablewith duplicates removed
-
distinctBy
default <U> Seq<T> distinctBy(@NonNull java.util.function.Function<? super T,? extends U> keyExtractor)
Description copied from interface:TraversableReturns a newTraversablecontaining the elements of this instance without duplicates, based on keys extracted from elements usingkeyExtractor.The first occurrence of each key is retained in the resulting sequence.
- Specified by:
distinctByin interfaceTraversable<T>- Type Parameters:
U- the type of key- Parameters:
keyExtractor- a function to extract keys for determining uniqueness- Returns:
- a new
Traversablewith duplicates removed based on keys
-
drop
default Seq<T> drop(int n)
Description copied from interface:TraversableReturns a newTraversablewithout the firstnelements, or an empty instance if this contains fewer thannelements.- Specified by:
dropin interfaceTraversable<T>- Parameters:
n- the number of elements to drop- Returns:
- a new instance excluding the first
nelements
-
dropRight
default Seq<T> dropRight(int n)
Description copied from interface:TraversableReturns a newTraversablewithout the lastnelements, or an empty instance if this contains fewer thannelements.- Specified by:
dropRightin interfaceTraversable<T>- Parameters:
n- the number of elements to drop from the end- Returns:
- a new instance excluding the last
nelements
-
dropUntil
default Seq<T> dropUntil(@NonNull java.util.function.Predicate<? super T> predicate)
Description copied from interface:TraversableReturns a newTraversablestarting from the first element that satisfies the givenpredicate, dropping all preceding elements.- Specified by:
dropUntilin interfaceTraversable<T>- Parameters:
predicate- a condition tested on each element- Returns:
- a new instance starting from the first element matching the predicate
-
dropWhile
default Seq<T> dropWhile(@NonNull java.util.function.Predicate<? super T> predicate)
Description copied from interface:TraversableReturns a newTraversablestarting from the first element that does not satisfy the givenpredicate, dropping all preceding elements.This is equivalent to
dropUntil(predicate.negate()), which is useful for method references that cannot be negated directly.- Specified by:
dropWhilein interfaceTraversable<T>- Parameters:
predicate- a condition tested on each element- Returns:
- a new instance starting from the first element not matching the predicate
-
filter
default Seq<T> filter(@NonNull java.util.function.Predicate<? super T> predicate)
Description copied from interface:TraversableReturns a new traversable containing only the elements that satisfy the given predicate.- Specified by:
filterin interfaceTraversable<T>- Parameters:
predicate- the condition to test elements- Returns:
- a traversable with elements matching the predicate
-
reject
default Seq<T> reject(@NonNull java.util.function.Predicate<? super T> predicate)
Description copied from interface:TraversableReturns a new traversable containing only the elements that do not satisfy the given predicate.This is equivalent to
filter(predicate.negate()).- Specified by:
rejectin interfaceTraversable<T>- Parameters:
predicate- the condition to test elements- Returns:
- a traversable with elements not matching the predicate
-
flatMap
default <U> Tree<U> flatMap(@NonNull java.util.function.Function<? super T,? extends java.lang.Iterable<? extends U>> mapper)
Description copied from interface:TraversableTransforms each element of this Traversable into anIterableof elements and flattens the resulting iterables into a single Traversable.- Specified by:
flatMapin interfaceTraversable<T>- Type Parameters:
U- the type of elements in the resulting Traversable- Parameters:
mapper- a function mapping elements to iterables- Returns:
- a new Traversable containing all elements produced by applying
mapperand flattening
-
foldRight
default <U> U foldRight(U zero, @NonNull java.util.function.BiFunction<? super T,? super U,? extends U> f)Description copied from interface:FoldableFolds the elements of this structure from the right, starting with the givenzerovalue and successively applying thecombinefunction to each element.Folding from the right means that elements are combined starting from the last element and associating each step with the accumulated result so far.
Example:
// Result: "!cba" List.of("a", "b", "c").foldRight("!", (x, acc) -> acc + x);- Specified by:
foldRightin interfaceFoldable<T>- Specified by:
foldRightin interfaceTraversable<T>- Type Parameters:
U- the type of the accumulated result- Parameters:
zero- the initial value to start folding withf- a function that combines the next element and the accumulated value- Returns:
- the folded result
-
groupBy
default <C> Map<C,Seq<T>> groupBy(@NonNull java.util.function.Function<? super T,? extends C> classifier)
Description copied from interface:TraversableGroups elements of thisTraversablebased on a classifier function.- Specified by:
groupByin interfaceTraversable<T>- Type Parameters:
C- The type of the group keys- Parameters:
classifier- A function that assigns each element to a group- Returns:
- A map where each key corresponds to a group of elements
- See Also:
Traversable.arrangeBy(Function)
-
grouped
default Iterator<Seq<T>> grouped(int size)
Description copied from interface:TraversableSplits thisTraversableinto consecutive blocks of the given size.Let
lengthbe the number of elements in thisTraversable:- If empty, the resulting
Iteratoris empty. - If
size <= length, the resultingIteratorcontainslength / sizeblocks of sizesizeand possibly a final smaller block of sizelength % size. - If
size > length, the resultingIteratorcontains a single block of sizelength.
Examples:
[].grouped(1) = [] [].grouped(0) throws [].grouped(-1) throws [1,2,3,4].grouped(2) = [[1,2],[3,4]] [1,2,3,4,5].grouped(2) = [[1,2],[3,4],[5]] [1,2,3,4].grouped(5) = [[1,2,3,4]]Note:
grouped(size)is equivalent tosliding(size, size).- Specified by:
groupedin interfaceTraversable<T>- Parameters:
size- the block size; must be positive- Returns:
- an
Iteratorover blocks of elements
- If empty, the resulting
-
hasDefiniteSize
default boolean hasDefiniteSize()
Description copied from interface:TraversableIndicates whether thisTraversablehas a known finite size.This should typically be implemented by concrete classes, not interfaces.
- Specified by:
hasDefiniteSizein interfaceTraversable<T>- Returns:
trueif the number of elements is finite and known,falseotherwise.
-
head
default T head()
Description copied from interface:TraversableReturns the first element of this non-emptyTraversable.- Specified by:
headin interfaceTraversable<T>- Returns:
- the first element
-
init
default Seq<T> init()
Description copied from interface:TraversableReturns all elements of this Traversable except the last one.This is the dual of
Traversable.tail().- Specified by:
initin interfaceTraversable<T>- Returns:
- a new instance containing all elements except the last
-
initOption
default Option<Seq<T>> initOption()
Description copied from interface:TraversableReturns all elements of this Traversable except the last one, wrapped in anOption.This is the dual of
Traversable.tailOption().- Specified by:
initOptionin interfaceTraversable<T>- Returns:
Some(traversable)if non-empty, orNoneif this Traversable is empty
-
isTraversableAgain
default boolean isTraversableAgain()
Description copied from interface:TraversableChecks if this Traversable can be traversed multiple times without side effects.Implementations should provide the correct behavior; this is not meant for interfaces alone.
- Specified by:
isTraversableAgainin interfaceTraversable<T>- Returns:
trueif this Traversable is guaranteed to be repeatably traversable,falseotherwise
-
iterator
default @NonNull Iterator<T> iterator()
Description copied from interface:TraversableReturns an iterator over the elements of this Traversable, implemented viaTraversable.head()andTraversable.tail(). Subclasses may override for a more efficient implementation.
-
map
default <U> Tree<U> map(@NonNull java.util.function.Function<? super T,? extends U> mapper)
Description copied from interface:TraversableTransforms the elements of this Traversable to a new type, preserving order if defined.
-
mapTo
default <U> Tree<U> mapTo(U value)
Description copied from interface:ValueMaps the underlying value to another fixed value.
-
mapToVoid
default Tree<java.lang.Void> mapToVoid()
Description copied from interface:ValueMaps the underlying value to Void
-
orElse
default Tree<T> orElse(@NonNull java.lang.Iterable<? extends T> other)
Description copied from interface:TraversableReturns thisTraversableif it is non-empty; otherwise, returns the given alternative.- Specified by:
orElsein interfaceTraversable<T>- Parameters:
other- an alternativeTraversableto return if this is empty- Returns:
- this
Traversableif non-empty, otherwiseother
-
orElse
default Tree<T> orElse(@NonNull java.util.function.Supplier<? extends java.lang.Iterable<? extends T>> supplier)
Description copied from interface:TraversableReturns thisTraversableif it is non-empty; otherwise, returns the result of evaluating the given supplier.- Specified by:
orElsein interfaceTraversable<T>- Parameters:
supplier- a supplier of an alternativeTraversableif this is empty- Returns:
- this
Traversableif non-empty, otherwise the result ofsupplier.get()
-
partition
default Tuple2<Seq<T>,Seq<T>> partition(@NonNull java.util.function.Predicate<? super T> predicate)
Description copied from interface:TraversableSplits thisTraversableinto two partitions according to a predicate.The first partition contains all elements that satisfy the predicate, and the second contains all elements that do not. The original iteration order is preserved.
- Specified by:
partitionin interfaceTraversable<T>- Parameters:
predicate- a predicate used to classify elements- Returns:
- a
Tuple2containing the two resultingTraversableinstances
-
peek
default Tree<T> peek(@NonNull 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.
-
replace
default Tree<T> replace(T currentElement, T newElement)
Description copied from interface:TraversableReplaces the first occurrence ofcurrentElementwithnewElement, if it exists.- Specified by:
replacein interfaceTraversable<T>- Parameters:
currentElement- the element to be replacednewElement- the replacement element- Returns:
- a new Traversable with the first occurrence of
currentElementreplaced bynewElement
-
replaceAll
default Tree<T> replaceAll(T currentElement, T newElement)
Description copied from interface:TraversableReplaces all occurrences ofcurrentElementwithnewElement.- Specified by:
replaceAllin interfaceTraversable<T>- Parameters:
currentElement- the element to be replacednewElement- the replacement element- Returns:
- a new Traversable with all occurrences of
currentElementreplaced bynewElement
-
retainAll
default Seq<T> retainAll(@NonNull java.lang.Iterable<? extends T> elements)
Description copied from interface:TraversableRetains only the elements from this Traversable that are contained in the givenelements.- Specified by:
retainAllin interfaceTraversable<T>- Parameters:
elements- the elements to keep- Returns:
- a new Traversable containing only the elements present in
elements, in their original order
-
scan
default Seq<T> scan(T zero, @NonNull java.util.function.BiFunction<? super T,? super T,? extends T> operation)
Description copied from interface:TraversableComputes a prefix scan of the elements of this Traversable.The neutral element
zeromay be applied more than once.- Specified by:
scanin interfaceTraversable<T>- Parameters:
zero- the neutral element for the operatoroperation- an associative binary operator- Returns:
- a new Traversable containing the prefix scan of the elements
-
scanLeft
default <U> Seq<U> scanLeft(U zero, @NonNull java.util.function.BiFunction<? super U,? super T,? extends U> operation)
Description copied from interface:TraversableProduces a collection containing cumulative results of applying the operator from left to right.Will not terminate for infinite collections. The results may vary across runs unless the collection is ordered.
- Specified by:
scanLeftin interfaceTraversable<T>- Type Parameters:
U- the type of the resulting elements- Parameters:
zero- the initial valueoperation- a binary operator applied to the intermediate result and each element- Returns:
- a new Traversable containing the cumulative results
-
scanRight
default <U> Seq<U> scanRight(U zero, @NonNull java.util.function.BiFunction<? super T,? super U,? extends U> operation)
Description copied from interface:TraversableProduces a collection containing cumulative results of applying the operator from right to left.The head of the resulting collection is the last cumulative result. Will not terminate for infinite collections. Results may vary across runs unless the collection is ordered.
- Specified by:
scanRightin interfaceTraversable<T>- Type Parameters:
U- the type of the resulting elements- Parameters:
zero- the initial valueoperation- a binary operator applied to each element and the intermediate result- Returns:
- a new Traversable containing the cumulative results
-
slideBy
default Iterator<Seq<T>> slideBy(@NonNull java.util.function.Function<? super T,?> classifier)
Description copied from interface:TraversablePartitions thisTraversableinto consecutive non-overlapping windows according to a classification function.Each window contains elements with the same class, as determined by
classifier. Two consecutive elements belong to the same window only ifclassifierreturns equal values for both. Otherwise, the current window ends and a new window begins with the next element.Examples:
[].slideBy(Function.identity()) = [] [1,2,3,4,4,5].slideBy(Function.identity()) = [[1],[2],[3],[4,4],[5]] [1,2,3,10,12,5,7,20,29].slideBy(x -> x / 10) = [[1,2,3],[10,12],[5,7],[20,29]]- Specified by:
slideByin interfaceTraversable<T>- Parameters:
classifier- A function classifying elements into groups- Returns:
- An
Iteratorof windows (grouped elements)
-
sliding
default Iterator<Seq<T>> sliding(int size)
Description copied from interface:TraversableSlides a window of a givensizeover thisTraversablewith a step size of 1.This is equivalent to calling
Traversable.sliding(int, int)with a step size of 1.- Specified by:
slidingin interfaceTraversable<T>- Parameters:
size- a positive window size- Returns:
- An
Iteratorof windows, each containing up tosizeelements
-
sliding
default Iterator<Seq<T>> sliding(int size, int step)
Description copied from interface:TraversableSlides a window of a specificsizewith a givenstepover thisTraversable.Examples:
[].sliding(1, 1) = [] [1,2,3,4,5].sliding(2, 3) = [[1,2],[4,5]] [1,2,3,4,5].sliding(2, 4) = [[1,2],[5]] [1,2,3,4,5].sliding(2, 5) = [[1,2]] [1,2,3,4].sliding(5, 3) = [[1,2,3,4],[4]]- Specified by:
slidingin interfaceTraversable<T>- Parameters:
size- a positive window sizestep- a positive step size- Returns:
- an
Iteratorof windows with the given size and step
-
span
default Tuple2<Seq<T>,Seq<T>> span(@NonNull java.util.function.Predicate<? super T> predicate)
Description copied from interface:TraversableSplits thisTraversableinto a prefix and remainder according to the givenpredicate.The first element of the returned
Tupleis the longest prefix of elements satisfyingpredicate, and the second element is the remaining elements.- Specified by:
spanin interfaceTraversable<T>- Parameters:
predicate- a predicate used to determine the prefix- Returns:
- a
Tuplecontaining the prefix and remainder
-
stringPrefix
default java.lang.String stringPrefix()
Description copied from interface:ValueReturns the name of this Value type, which is used by toString().- Specified by:
stringPrefixin interfaceValue<T>- Returns:
- This type name.
-
tail
default Seq<T> tail()
Description copied from interface:TraversableReturns a newTraversablewithout its first element.- Specified by:
tailin interfaceTraversable<T>- Returns:
- a new
Traversablecontaining all elements except the first
-
tailOption
default Option<Seq<T>> tailOption()
Description copied from interface:TraversableReturns a newTraversablewithout its first element as anOption.- Specified by:
tailOptionin interfaceTraversable<T>- Returns:
Some(traversable)if non-empty, otherwiseNone
-
take
default Seq<T> take(int n)
Description copied from interface:TraversableReturns the firstnelements of thisTraversable, or all elements ifnexceeds the length.Equivalent to
sublist(0, max(0, min(length(), n))), but safe forn < 0orn > length().If
n < 0, an empty instance is returned. Ifn > length(), the full instance is returned.- Specified by:
takein interfaceTraversable<T>- Parameters:
n- the number of elements to take- Returns:
- a new
Traversablecontaining the firstnelements
-
takeRight
default Seq<T> takeRight(int n)
Description copied from interface:TraversableReturns the lastnelements of thisTraversable, or all elements ifnexceeds the length.Equivalent to
sublist(max(0, length() - n), length()), but safe forn < 0orn > length().If
n < 0, an empty instance is returned. Ifn > length(), the full instance is returned.- Specified by:
takeRightin interfaceTraversable<T>- Parameters:
n- the number of elements to take from the end- Returns:
- a new
Traversablecontaining the lastnelements
-
takeUntil
default Seq<T> takeUntil(@NonNull java.util.function.Predicate<? super T> predicate)
Description copied from interface:TraversableTakes elements from thisTraversableuntil the given predicate holds for an element.Equivalent to
takeWhile(predicate.negate()), but useful when using method references that cannot be negated directly.- Specified by:
takeUntilin interfaceTraversable<T>- Parameters:
predicate- a condition tested sequentially on the elements- Returns:
- a new
Traversablecontaining all elements before the first one that satisfies the predicate
-
takeWhile
default Seq<T> takeWhile(@NonNull java.util.function.Predicate<? super T> predicate)
Description copied from interface:TraversableTakes elements from thisTraversablewhile the given predicate holds.- Specified by:
takeWhilein interfaceTraversable<T>- Parameters:
predicate- a condition tested sequentially on the elements- Returns:
- a new
Traversablecontaining all elements up to (but not including) the first one that does not satisfy the predicate
-
unzip
default <T1,T2> Tuple2<Tree<T1>,Tree<T2>> unzip(@NonNull java.util.function.Function<? super T,Tuple2<? extends T1,? extends T2>> unzipper)
Description copied from interface:TraversableUnzips the elements of thisTraversableby mapping each element to a pair and splitting them into two separateTraversablecollections.- Specified by:
unzipin interfaceTraversable<T>- Type Parameters:
T1- type of the first element in the resulting pairsT2- type of the second element in the resulting pairs- Parameters:
unzipper- a function that maps elements of thisTraversableto pairs- Returns:
- a
Tuple2containing twoTraversablecollections with the split elements
-
unzip3
default <T1,T2,T3> Tuple3<Tree<T1>,Tree<T2>,Tree<T3>> unzip3(@NonNull java.util.function.Function<? super T,Tuple3<? extends T1,? extends T2,? extends T3>> unzipper)
Description copied from interface:TraversableUnzips the elements of thisTraversableby mapping each element to a triple and splitting them into three separateTraversablecollections.- Specified by:
unzip3in interfaceTraversable<T>- Type Parameters:
T1- type of the first element in the resulting triplesT2- type of the second element in the resulting triplesT3- type of the third element in the resulting triples- Parameters:
unzipper- a function that maps elements of thisTraversableto triples- Returns:
- a
Tuple3containing threeTraversablecollections with the split elements
-
zip
default <U> Tree<Tuple2<T,U>> zip(@NonNull java.lang.Iterable<? extends U> that)
Description copied from interface:TraversableReturns aTraversableformed by pairing elements of thisTraversablewith elements of anotherIterable. Pairing stops when either collection runs out of elements; any remaining elements in the longer collection are ignored.The length of the resulting
Traversableis the minimum of the lengths of thisTraversableandthat.- Specified by:
zipin interfaceTraversable<T>- Type Parameters:
U- the type of elements in the second half of each pair- Parameters:
that- anIterableproviding the second element of each pair- Returns:
- a new
Traversablecontaining pairs of corresponding elements
-
zipWith
default <U,R> Tree<R> zipWith(@NonNull java.lang.Iterable<? extends U> that, java.util.function.BiFunction<? super T,? super U,? extends R> mapper)
Description copied from interface:TraversableReturns aTraversableby combining elements of thisTraversablewith elements of anotherIterableusing a mapping function. Pairing stops when either collection runs out of elements.The length of the resulting
Traversableis the minimum of the lengths of thisTraversableandthat.- Specified by:
zipWithin interfaceTraversable<T>- Type Parameters:
U- the type of elements in the second parameter of the mapperR- the type of elements in the resultingTraversable- Parameters:
that- anIterableproviding the second parameter of the mappermapper- a function that combines elements from this andthatinto a new element- Returns:
- a new
Traversablecontaining mapped elements
-
zipAll
default <U> Tree<Tuple2<T,U>> zipAll(@NonNull java.lang.Iterable<? extends U> that, T thisElem, U thatElem)
Description copied from interface:TraversableReturns aTraversableformed by pairing elements of thisTraversablewith elements of anotherIterable, filling in placeholder elements when one collection is shorter than the other.The length of the resulting
Traversableis the maximum of the lengths of thisTraversableandthat.If this
Traversableis shorter thanthat,thisElemis used as a filler. Conversely, ifthatis shorter,thatElemis used.- Specified by:
zipAllin interfaceTraversable<T>- Type Parameters:
U- the type of elements in the second half of each pair- Parameters:
that- anIterableproviding the second element of each pairthisElem- the element used to fill missing values if thisTraversableis shorter thanthatthatElem- the element used to fill missing values ifthatis shorter than thisTraversable- Returns:
- a new
Traversablecontaining pairs of elements, including fillers as needed
-
zipWithIndex
default Tree<Tuple2<T,java.lang.Integer>> zipWithIndex()
Description copied from interface:TraversableZips thisTraversablewith its indices, starting at 0.- Specified by:
zipWithIndexin interfaceTraversable<T>- Returns:
- a new
Traversablecontaining each element paired with its index
-
zipWithIndex
default <U> Tree<U> zipWithIndex(@NonNull java.util.function.BiFunction<? super T,? super java.lang.Integer,? extends U> mapper)
Description copied from interface:TraversableZips thisTraversablewith its indices and maps the resulting pairs using the provided mapper.- Specified by:
zipWithIndexin interfaceTraversable<T>- Type Parameters:
U- the type of elements in the resultingTraversable- Parameters:
mapper- a function mapping an element and its index to a new element- Returns:
- a new
Traversablecontaining the mapped elements
-
equals
boolean equals(java.lang.Object o)
Description copied from interface:TraversableDetermines whether this collection is equal to the given object.In Vavr, there are four basic collection types:
Seq– sequential elementsSet– distinct elementsMap– key-value pairsMultimap– keys mapped to multiple values
- They are of the same collection type (Seq, Set, Map, Multimap)
- They contain the same elements
- For
Seq, the element order is the same
For
MapandMultimap, two entries(key1, value1)and(key2, value2)are equal if both their keys and values are equal.Additional notes:
- No collection equals
null(e.g.,Queue(1) != null) - Null elements are allowed and treated as expected
(e.g.,
List(null, 1) == Stream(null, 1),HashMap((null,1)) == LinkedHashMap((null,1))) - Element order matters only for
Seq - Other collection classes are equal if their types and elements (in iteration order) are equal
- Iterators are compared by reference only
-
hashCode
int hashCode()
Description copied from interface:TraversableReturns the hash code of this collection.Vavr distinguishes between collections with predictable iteration order (like
Seq) and collections with arbitrary iteration order (likeSet,Map, andMultimap). In all cases, the hash of an empty collection is defined as1.For collections with predictable iteration order, the hash is computed as:
int hash = 1; for (T t : this) { hash = hash * 31 + Objects.hashCode(t); }For collections with arbitrary iteration order, the hash is computed to be independent of element order:
int hash = 1; for (T t : this) { hash += Objects.hashCode(t); }Note that these algorithms may change in future Vavr versions. Hash codes are generally not cached, unlike size/length, because caching would increase memory usage due to persistent tree-based structures. Computing the hash code is linear in time, O(n). For frequently re-used collections (e.g., as
HashMapkeys), caching can be done externally using a wrapper, for example:{@code public final class Hashed{ private final K key; private final Lazy hashCode; public Hashed(K key) { this.key = key; this.hashCode = Lazy.of(() -> Objects.hashCode(key)); } public K key() { return key; }
-
toString
java.lang.String toString()
Description copied from interface:ValueClarifies that values have a proper toString() method implemented.See Object.toString().
-
draw
java.lang.String draw()
Creates a neat 2-dimensional drawing of a tree. Unicode characters are used to draw node junctions.- Returns:
- A nice string representation of the tree.
-
-