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 class
Tree.Empty<T>
The empty tree.static class
Tree.Node<T>
Represents a tree node.static class
Tree.Order
Tree traversal order.
-
Field Summary
Fields Modifier and Type Field Description static long
serialVersionUID
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Default Methods Modifier and Type Method Description default int
branchCount()
Counts the number of branches of this tree.static <T,ID>
List<Tree.Node<T>>build(java.lang.Iterable<? extends T> source, java.util.function.Function<? super T,? extends ID> idMapper, java.util.function.Function<? super T,? extends ID> parentMapper)
Build aList
with roots ofTree
from flat source.default <R> Tree<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
.static <T> java.util.stream.Collector<T,java.util.ArrayList<T>,Tree<T>>
collector()
Returns aCollector
which may be used in conjunction withStream.collect(java.util.stream.Collector)
to obtain aTree
.default Seq<T>
distinct()
Returns a new version of this which contains no duplicates.default Seq<T>
distinctBy(java.util.Comparator<? super T> comparator)
Returns a new version of this which contains no duplicates.default <U> Seq<T>
distinctBy(java.util.function.Function<? super T,? extends U> keyExtractor)
Returns a new version of this which contains no duplicates.java.lang.String
draw()
Creates a neat 2-dimensional drawing of a tree.default Seq<T>
drop(int n)
Drops the first n elements of this or all elements, if this length < n.default Seq<T>
dropRight(int n)
Drops the last n elements of this or all elements, if this length < n.default Seq<T>
dropUntil(java.util.function.Predicate<? super T> predicate)
Drops elements until the predicate holds for the current element.default Seq<T>
dropWhile(java.util.function.Predicate<? super T> predicate)
Drops elements while the predicate holds for the current element.static <T> Tree.Empty<T>
empty()
Returns the singleton empty tree.boolean
equals(java.lang.Object o)
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.static <T> Tree<T>
fill(int n, java.util.function.Supplier<? extends T> s)
Returns a Tree containingn
values supplied by a given Suppliers
.static <T> Tree<T>
fill(int n, T element)
Returns a Tree containingn
times the givenelement
default Seq<T>
filter(java.util.function.Predicate<? super T> predicate)
Returns a new traversable consisting of all elements which satisfy the given predicate.default <U> Tree<U>
flatMap(java.util.function.Function<? super T,? extends java.lang.Iterable<? extends U>> mapper)
FlatMaps this Traversable.default <U> U
foldRight(U zero, java.util.function.BiFunction<? super T,? super U,? extends U> f)
Folds this elements from the right, starting withzero
and successively callingcombine
.List<Tree.Node<T>>
getChildren()
Returns the children of this tree.T
getValue()
Gets the value of this tree.default <C> Map<C,Seq<T>>
groupBy(java.util.function.Function<? super T,? extends C> classifier)
Groups this elements by classifying the elements.default Iterator<Seq<T>>
grouped(int size)
Groups thisTraversable
into fixed size blocks.default boolean
hasDefiniteSize()
Checks if this Traversable is known to have a finite size.int
hashCode()
Returns the hash code of this collection.default T
head()
Returns the first element of a non-empty Traversable.default Seq<T>
init()
Dual of Traversable.tail(), returning all elements except the last.default Option<Seq<T>>
initOption()
Dual of Traversable.tailOption(), returning all elements except the last asOption
.default boolean
isAsync()
ATree
is computed synchronously.default boolean
isBranch()
Checks if this Tree is a branch.default boolean
isDistinct()
Checks if this Traversable may consist of distinct elements only.default boolean
isLazy()
ATree
is computed eagerly.boolean
isLeaf()
Checks if this Tree is a leaf.default boolean
isSequential()
Checks if the elements of this Traversable appear in encounter order.default boolean
isTraversableAgain()
Checks if this Traversable can be repeatedly traversed.default Iterator<T>
iterator()
An iterator by means of head() and tail().default Iterator<T>
iterator(Tree.Order order)
Traverses this tree values in a specificTree.Order
.default int
leafCount()
Counts the number of leaves of this tree.default <U> Tree<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.static <T> Tree<T>
narrow(Tree<? extends T> tree)
Narrows a widenedTree<? extends T>
toTree<T>
by performing a type-safe cast.default int
nodeCount()
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... values)
Creates a Tree of the given elements.static <T> Tree.Node<T>
of(T value, Tree.Node<T>... children)
Returns a new Node containing the given value and having the given children.static <T> Tree.Node<T>
of(T value, 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(java.lang.Iterable<? extends T> iterable)
Creates a Tree of the given elements.static <T> Tree<T>
ofAll(java.util.stream.Stream<? extends T> javaStream)
Creates a Tree that contains the elements of the givenStream
.default Tree<T>
orElse(java.lang.Iterable<? extends T> other)
Returns thisTraversable
if it is nonempty, otherwise return the alternative.default Tree<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.default Tuple2<Seq<T>,Seq<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.default Tree<T>
peek(java.util.function.Consumer<? super T> action)
Performs the givenaction
on the first element if this is an eager implementation.static <T> Tree.Node<T>
recurse(T seed, java.util.function.Function<? super T,? extends java.lang.Iterable<? extends T>> descend)
Recursively builds a non-emptyTree
, starting with the givenseed
value and proceeding in depth-first order.default Seq<T>
reject(java.util.function.Predicate<? super T> predicate)
Returns a new traversable consisting of all elements which do not satisfy the given predicate.default Tree<T>
replace(T currentElement, T newElement)
Replaces the first occurrence (if exists) of the given currentElement with newElement.default Tree<T>
replaceAll(T currentElement, T newElement)
Replaces all occurrences of the given currentElement with newElement.default Seq<T>
retainAll(java.lang.Iterable<? extends T> elements)
Keeps all occurrences of the given elements from this.default Seq<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.default <U> Seq<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.default <U> Seq<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 Iterator<Seq<T>>
slideBy(java.util.function.Function<? super T,?> classifier)
Slides a non-overlapping window of a variable size over thisTraversable
.default Iterator<Seq<T>>
sliding(int size)
Slides a window of a specificsize
and step size 1 over thisTraversable
by callingTraversable.sliding(int, int)
.default Iterator<Seq<T>>
sliding(int size, int step)
Slides a window of a specificsize
andstep
size over thisTraversable
.default Tuple2<Seq<T>,Seq<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.lang.String
stringPrefix()
Returns the name of this Value type, which is used by toString().static <T> Tree<T>
tabulate(int n, java.util.function.Function<? super java.lang.Integer,? extends T> f)
Returns a Tree containingn
values of a given Functionf
over a range of integer values from 0 ton - 1
.default Seq<T>
tail()
Drops the first element of a non-empty Traversable.default Option<Seq<T>>
tailOption()
Drops the first element of a non-empty Traversable and returns anOption
.default Seq<T>
take(int n)
Takes the first n elements of this or all elements, if this length < n.default Seq<T>
takeRight(int n)
Takes the last n elements of this or all elements, if this length < n.default Seq<T>
takeUntil(java.util.function.Predicate<? super T> predicate)
Takes elements until the predicate holds for the current element.default Seq<T>
takeWhile(java.util.function.Predicate<? super T> predicate)
Takes elements while the predicate holds for the current element.java.lang.String
toLispString()
Creates a Lisp-like representation of thisTree
.java.lang.String
toString()
Clarifies that values have a proper toString() method implemented.default <U> U
transform(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(Tree.Order order)
Traverses this tree in a specific order.default <T1,T2>
Tuple2<Tree<T1>,Tree<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.default <T1,T2,T3>
Tuple3<Tree<T1>,Tree<T2>,Tree<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.default Seq<T>
values()
Traverses this tree values inTree.Order.PRE_ORDER
.default Seq<T>
values(Tree.Order order)
Traverses this tree values in a specific order.default <U> Tree<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.default <U> Tree<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.default <U,R>
Tree<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.default Tree<Tuple2<T,java.lang.Integer>>
zipWithIndex()
Zips this traversable with its indices.default <U> Tree<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.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
- See Also:
- Constant Field Values
-
-
Method Detail
-
collector
static <T> java.util.stream.Collector<T,java.util.ArrayList<T>,Tree<T>> collector()
Returns aCollector
which 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
tree
instance 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, 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
static <T> Tree.Node<T> of(T value, 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... 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
- ifvalues
is null
-
ofAll
static <T> Tree<T> ofAll(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
- ifelements
is null
-
ofAll
static <T> Tree<T> ofAll(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, java.util.function.Function<? super java.lang.Integer,? extends T> f)
Returns a Tree containingn
values of a given Functionf
over 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
- iff
is null
-
fill
static <T> Tree<T> fill(int n, java.util.function.Supplier<? extends T> s)
Returns a Tree containingn
values 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
- ifs
is null
-
fill
static <T> Tree<T> fill(int n, T element)
Returns a Tree containingn
times 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, java.util.function.Function<? super T,? extends java.lang.Iterable<? extends T>> descend)
Recursively builds a non-emptyTree
, starting with the givenseed
value and proceeding in depth-first order.The children of a node are created by
- applying the
descend
function 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
Tree
instance - Throws:
java.lang.NullPointerException
- ifdescend
is null
- applying the
-
build
static <T,ID> List<Tree.Node<T>> build(java.lang.Iterable<? extends T> source, java.util.function.Function<? super T,? extends ID> idMapper, java.util.function.Function<? super T,? extends ID> parentMapper)
Build aList
with roots ofTree
from flat source.parentMapper
must returnnull
for 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
List
instance with non-emptyTree
instances - Throws:
java.lang.NullPointerException
- ifsource
,idMapper
orparentMapper
is null
-
collect
default <R> Tree<R> collect(PartialFunction<? super T,? extends R> partialFunction)
Description copied from interface:Traversable
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
).- Specified by:
collect
in interfaceTraversable<T>
- 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
-
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()
ATree
is computed synchronously.
-
isDistinct
default boolean isDistinct()
Description copied from interface:Traversable
Checks if this Traversable may consist of distinct elements only.- Specified by:
isDistinct
in interfaceTraversable<T>
- Returns:
- true if this Traversable may consist of distinct elements only, false otherwise.
-
isLazy
default boolean isLazy()
ATree
is computed eagerly.
-
isSequential
default boolean isSequential()
Description copied from interface:Traversable
Checks if the elements of this Traversable appear in encounter order.- Specified by:
isSequential
in interfaceTraversable<T>
- Returns:
- true, if the insertion order of elements is preserved, false otherwise.
-
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
Tree
as Lisp-string, i.e. represented as list of lists.
-
transform
default <U> U transform(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
- iff
is 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(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(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:Traversable
Returns a new version of this which contains no duplicates. Elements are compared usingequals
.- Specified by:
distinct
in interfaceTraversable<T>
- Returns:
- a new
Traversable
containing this elements without duplicates
-
distinctBy
default Seq<T> distinctBy(java.util.Comparator<? super T> comparator)
Description copied from interface:Traversable
Returns a new version of this which contains no duplicates. Elements are compared using the givencomparator
.- Specified by:
distinctBy
in interfaceTraversable<T>
- Parameters:
comparator
- A comparator- Returns:
- a new
Traversable
containing this elements without duplicates
-
distinctBy
default <U> Seq<T> distinctBy(java.util.function.Function<? super T,? extends U> keyExtractor)
Description copied from interface:Traversable
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.
- Specified by:
distinctBy
in interfaceTraversable<T>
- Type Parameters:
U
- key type- Parameters:
keyExtractor
- A key extractor- Returns:
- a new
Traversable
containing this elements without duplicates
-
drop
default Seq<T> drop(int n)
Description copied from interface:Traversable
Drops the first n elements of this or all elements, if this length < n.- Specified by:
drop
in interfaceTraversable<T>
- 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
default Seq<T> dropRight(int n)
Description copied from interface:Traversable
Drops the last n elements of this or all elements, if this length < n.- Specified by:
dropRight
in interfaceTraversable<T>
- 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
default Seq<T> dropUntil(java.util.function.Predicate<? super T> predicate)
Description copied from interface:Traversable
Drops elements until the predicate holds for the current element.- Specified by:
dropUntil
in interfaceTraversable<T>
- 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.
-
dropWhile
default Seq<T> dropWhile(java.util.function.Predicate<? super T> predicate)
Description copied from interface:Traversable
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.- Specified by:
dropWhile
in interfaceTraversable<T>
- 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.
-
filter
default Seq<T> filter(java.util.function.Predicate<? super T> predicate)
Description copied from interface:Traversable
Returns a new traversable consisting of all elements which satisfy the given predicate.- Specified by:
filter
in interfaceTraversable<T>
- Parameters:
predicate
- A predicate- Returns:
- a new traversable
-
reject
default Seq<T> reject(java.util.function.Predicate<? super T> predicate)
Description copied from interface:Traversable
Returns a new traversable consisting of all elements which do not satisfy the given predicate.The default implementation is equivalent to
filter(predicate.negate()
- Specified by:
reject
in interfaceTraversable<T>
- Parameters:
predicate
- A predicate- Returns:
- a new traversable
-
flatMap
default <U> Tree<U> flatMap(java.util.function.Function<? super T,? extends java.lang.Iterable<? extends U>> mapper)
Description copied from interface:Traversable
FlatMaps this Traversable.- Specified by:
flatMap
in interfaceTraversable<T>
- Type Parameters:
U
- The resulting component type.- Parameters:
mapper
- A mapper- Returns:
- A new Traversable instance.
-
foldRight
default <U> U foldRight(U zero, java.util.function.BiFunction<? super T,? super U,? extends U> f)
Description copied from interface:Foldable
Folds this elements from the right, starting withzero
and successively callingcombine
.Example:
// = "!cba" List("a", "b", "c").foldRight("!", (x, xs) -> xs + x)
-
groupBy
default <C> Map<C,Seq<T>> groupBy(java.util.function.Function<? super T,? extends C> classifier)
Description copied from interface:Traversable
Groups this elements by classifying the elements.- Specified by:
groupBy
in interfaceTraversable<T>
- Type Parameters:
C
- classified class type- Parameters:
classifier
- A function which classifies elements into classes- Returns:
- A Map containing the grouped elements
- See Also:
Traversable.arrangeBy(Function)
-
grouped
default Iterator<Seq<T>> grouped(int size)
Description copied from interface:Traversable
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 Traversable.sliding(int, int), i.e.grouped(size)
is the same assliding(size, size)
.- Specified by:
grouped
in interfaceTraversable<T>
- Parameters:
size
- a positive block size- Returns:
- A new Iterator of grouped blocks of the given size
- If
-
hasDefiniteSize
default boolean hasDefiniteSize()
Description copied from interface:Traversable
Checks if this Traversable is known to have a finite size.This method should be implemented by classes only, i.e. not by interfaces.
- Specified by:
hasDefiniteSize
in interfaceTraversable<T>
- Returns:
- true, if this Traversable is known to have a finite size, false otherwise.
-
head
default T head()
Description copied from interface:Traversable
Returns the first element of a non-empty Traversable.- Specified by:
head
in interfaceTraversable<T>
- Returns:
- The first element of this Traversable.
-
init
default Seq<T> init()
Description copied from interface:Traversable
Dual of Traversable.tail(), returning all elements except the last.- Specified by:
init
in interfaceTraversable<T>
- Returns:
- a new instance containing all elements except the last.
-
initOption
default Option<Seq<T>> initOption()
Description copied from interface:Traversable
Dual of Traversable.tailOption(), returning all elements except the last asOption
.- Specified by:
initOption
in interfaceTraversable<T>
- Returns:
Some(traversable)
orNone
if this is empty.
-
isTraversableAgain
default boolean isTraversableAgain()
Description copied from interface:Traversable
Checks if this Traversable can be repeatedly traversed.This method should be implemented by classes only, i.e. not by interfaces.
- Specified by:
isTraversableAgain
in interfaceTraversable<T>
- Returns:
- true, if this Traversable is known to be traversable repeatedly, false otherwise.
-
iterator
default Iterator<T> iterator()
Description copied from interface:Traversable
An iterator by means of head() and tail(). Subclasses may want to override this method.
-
map
default <U> Tree<U> map(java.util.function.Function<? super T,? extends U> mapper)
Description copied from interface:Traversable
Maps the elements of thisTraversable
to elements of a new type preserving their order, if any.
-
orElse
default Tree<T> orElse(java.lang.Iterable<? extends T> other)
Description copied from interface:Traversable
Returns thisTraversable
if it is nonempty, otherwise return the alternative.- Specified by:
orElse
in interfaceTraversable<T>
- Parameters:
other
- An alternativeTraversable
- Returns:
- this
Traversable
if it is nonempty, otherwise return the alternative.
-
orElse
default Tree<T> orElse(java.util.function.Supplier<? extends java.lang.Iterable<? extends T>> supplier)
Description copied from interface:Traversable
Returns thisTraversable
if it is nonempty, otherwise return the result of evaluating supplier.- Specified by:
orElse
in interfaceTraversable<T>
- Parameters:
supplier
- An alternativeTraversable
supplier- Returns:
- this
Traversable
if it is nonempty, otherwise return the result of evaluating supplier.
-
partition
default Tuple2<Seq<T>,Seq<T>> partition(java.util.function.Predicate<? super T> predicate)
Description copied from interface:Traversable
Creates a partition of thisTraversable
by splitting this elements in two in distinct traversables according to a predicate.- Specified by:
partition
in interfaceTraversable<T>
- 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.
-
peek
default Tree<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.
-
replace
default Tree<T> replace(T currentElement, T newElement)
Description copied from interface:Traversable
Replaces the first occurrence (if exists) of the given currentElement with newElement.- Specified by:
replace
in interfaceTraversable<T>
- 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
default Tree<T> replaceAll(T currentElement, T newElement)
Description copied from interface:Traversable
Replaces all occurrences of the given currentElement with newElement.- Specified by:
replaceAll
in interfaceTraversable<T>
- 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
default Seq<T> retainAll(java.lang.Iterable<? extends T> elements)
Description copied from interface:Traversable
Keeps all occurrences of the given elements from this.- Specified by:
retainAll
in interfaceTraversable<T>
- Parameters:
elements
- Elements to be kept.- Returns:
- a Traversable containing all occurrences of the given elements.
-
scan
default Seq<T> scan(T zero, java.util.function.BiFunction<? super T,? super T,? extends T> operation)
Description copied from interface:Traversable
Computes a prefix scan of the elements of the collection. Note: The neutral element z may be applied more than once.- Specified by:
scan
in interfaceTraversable<T>
- 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
-
scanLeft
default <U> Seq<U> scanLeft(U zero, java.util.function.BiFunction<? super U,? super T,? extends U> operation)
Description copied from interface:Traversable
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.- Specified by:
scanLeft
in interfaceTraversable<T>
- 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
-
scanRight
default <U> Seq<U> scanRight(U zero, java.util.function.BiFunction<? super T,? super U,? extends U> operation)
Description copied from interface:Traversable
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.- Specified by:
scanRight
in interfaceTraversable<T>
- 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
-
slideBy
default Iterator<Seq<T>> slideBy(java.util.function.Function<? super T,?> classifier)
Description copied from interface:Traversable
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]]
- Specified by:
slideBy
in interfaceTraversable<T>
- Parameters:
classifier
- A function which classifies elements into classes- Returns:
- A new Iterator of windows of the grouped elements
-
sliding
default Iterator<Seq<T>> sliding(int size)
Description copied from interface:Traversable
Slides a window of a specificsize
and step size 1 over thisTraversable
by callingTraversable.sliding(int, int)
.- Specified by:
sliding
in interfaceTraversable<T>
- Parameters:
size
- a positive window size- Returns:
- a new Iterator of windows of a specific size using step size 1
-
sliding
default Iterator<Seq<T>> sliding(int size, int step)
Description copied from interface:Traversable
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]]
- Specified by:
sliding
in interfaceTraversable<T>
- 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
-
span
default Tuple2<Seq<T>,Seq<T>> span(java.util.function.Predicate<? super T> predicate)
Description copied from interface:Traversable
Returns a tuple where the first element is the longest prefix of elements that satisfy the givenpredicate
and the second element is the remainder.- Specified by:
span
in interfaceTraversable<T>
- Parameters:
predicate
- A predicate.- Returns:
- a
Tuple
containing the longest prefix of elements that satisfy p and the remainder.
-
stringPrefix
default java.lang.String stringPrefix()
Description copied from interface:Value
Returns the name of this Value type, which is used by toString().- Specified by:
stringPrefix
in interfaceValue<T>
- Returns:
- This type name.
-
tail
default Seq<T> tail()
Description copied from interface:Traversable
Drops the first element of a non-empty Traversable.- Specified by:
tail
in interfaceTraversable<T>
- Returns:
- A new instance of Traversable containing all elements except the first.
-
tailOption
default Option<Seq<T>> tailOption()
Description copied from interface:Traversable
Drops the first element of a non-empty Traversable and returns anOption
.- Specified by:
tailOption
in interfaceTraversable<T>
- Returns:
Some(traversable)
orNone
if this is empty.
-
take
default Seq<T> take(int n)
Description copied from interface:Traversable
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.- Specified by:
take
in interfaceTraversable<T>
- 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
default Seq<T> takeRight(int n)
Description copied from interface:Traversable
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.- Specified by:
takeRight
in interfaceTraversable<T>
- 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
default Seq<T> takeUntil(java.util.function.Predicate<? super T> predicate)
Description copied from interface:Traversable
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.- Specified by:
takeUntil
in interfaceTraversable<T>
- 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.
-
takeWhile
default Seq<T> takeWhile(java.util.function.Predicate<? super T> predicate)
Description copied from interface:Traversable
Takes elements while the predicate holds for the current element.- Specified by:
takeWhile
in interfaceTraversable<T>
- 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.
-
unzip
default <T1,T2> Tuple2<Tree<T1>,Tree<T2>> unzip(java.util.function.Function<? super T,Tuple2<? extends T1,? extends T2>> unzipper)
Description copied from interface:Traversable
Unzips this elements by mapping this elements to pairs which are subsequently split into two distinct sets.- Specified by:
unzip
in interfaceTraversable<T>
- 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
-
unzip3
default <T1,T2,T3> Tuple3<Tree<T1>,Tree<T2>,Tree<T3>> unzip3(java.util.function.Function<? super T,Tuple3<? extends T1,? extends T2,? extends T3>> unzipper)
Description copied from interface:Traversable
Unzips this elements by mapping this elements to triples which are subsequently split into three distinct sets.- Specified by:
unzip3
in interfaceTraversable<T>
- 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
-
zip
default <U> Tree<Tuple2<T,U>> zip(java.lang.Iterable<? extends U> that)
Description copied from interface:Traversable
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.- Specified by:
zip
in interfaceTraversable<T>
- 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.
-
zipWith
default <U,R> Tree<R> zipWith(java.lang.Iterable<? extends U> that, java.util.function.BiFunction<? super T,? super U,? extends R> mapper)
Description copied from interface:Traversable
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.- Specified by:
zipWith
in interfaceTraversable<T>
- 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.
-
zipAll
default <U> Tree<Tuple2<T,U>> zipAll(java.lang.Iterable<? extends U> that, T thisElem, U thatElem)
Description copied from interface:Traversable
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.
- Specified by:
zipAll
in interfaceTraversable<T>
- 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.
-
zipWithIndex
default Tree<Tuple2<T,java.lang.Integer>> zipWithIndex()
Description copied from interface:Traversable
Zips this traversable with its indices.- Specified by:
zipWithIndex
in interfaceTraversable<T>
- Returns:
- A new traversable containing all elements of this traversable paired with their index, starting with 0.
-
zipWithIndex
default <U> Tree<U> zipWithIndex(java.util.function.BiFunction<? super T,? super java.lang.Integer,? extends U> mapper)
Description copied from interface:Traversable
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.- Specified by:
zipWithIndex
in interfaceTraversable<T>
- 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.
-
equals
boolean equals(java.lang.Object o)
Description copied from interface:Traversable
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.
-
hashCode
int hashCode()
Description copied from interface:Traversable
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()) + ")"; } }
-
toString
java.lang.String toString()
Description copied from interface:Value
Clarifies 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.
-
-