Interface Traversable<T>

Type Parameters:
T - Component type
All Superinterfaces:
Foldable<T>, Iterable<T>, Value<T>
All Known Subinterfaces:
BitSet<T>, IndexedSeq<T>, Iterator<T>, LinearSeq<T>, List<T>, Map<K,V>, Multimap<K,V>, Seq<T>, Set<T>, SortedMap<K,V>, SortedMultimap<K,V>, SortedSet<T>, Stream<T>, Tree<T>
All Known Implementing Classes:
Array, CharSeq, HashMap, HashMultimap, HashSet, LinkedHashMap, LinkedHashMultimap, LinkedHashSet, List.Cons, List.Nil, PriorityQueue, Queue, Stream.Cons, Stream.Empty, Tree.Empty, Tree.Node, TreeMap, TreeMultimap, TreeSet, Vector

public interface Traversable<T> extends Foldable<T>, Value<T>
An interface for inherently recursive, multi-valued data structures. The order of elements is determined by Iterable.iterator(), which may vary each time it is called.

Basic operations:

Iteration: Numeric operations: Reduction/Folding: Selection: Tests: Transformation:
Author:
Daniel Dietrich and others
  • Method Details

    • narrow

      static <T> Traversable<T> narrow(Traversable<? extends T> traversable)
      Narrows a widened Traversable<? extends T> to Traversable<T> by performing a type-safe cast. This is eligible because immutable/read-only collections are covariant.
      Type Parameters:
      T - Component type of the Traversable.
      Parameters:
      traversable - An Traversable.
      Returns:
      the given traversable instance as narrowed type Traversable<T>.
    • arrangeBy

      default <K> Option<Map<K,T>> arrangeBy(Function<? super T,? extends K> getKey)
      Matches each element with a unique key that you extract from it. If the same key is present twice, the function will return None.
      Type Parameters:
      K - key class type
      Parameters:
      getKey - A function which extracts a key from elements
      Returns:
      A Map containing the elements arranged by their keys.
      Throws:
      NullPointerException - if getKey is null.
      See Also:
    • average

      default Option<Double> average()
      Calculates the average of this elements, assuming that the element type is Number. Since we do not know if the component type T is of type Number, the average() call might throw at runtime (see examples below).

      Examples:

      
       List.empty().average()                       // = None
       List.of(1, 2, 3).average()                   // = Some(2.0)
       List.of(1.0, 10e100, 2.0, -10e100).average() // = Some(0.75)
       List.of(1.0, Double.NaN).average()           // = NaN
       List.of("apple", "pear").average()           // throws
       
      Please note that Java's DoubleStream.average() uses the Kahan summation algorithm (also known as compensated summation), which has known limitations.

      Vavr uses Neumaier's modification of the Kahan algorithm, which yields better results.

      
       // = OptionalDouble(0.0) (wrong)
       j.u.s.DoubleStream.of(1.0, 10e100, 2.0, -10e100).average()
      
       // = Some(0.75) (correct)
       List.of(1.0, 10e100, 2.0, -10e100).average()
       
      Returns:
      Some(average) or None, if there are no elements
      Throws:
      UnsupportedOperationException - if this elements are not numeric
    • collect

      <R> Traversable<R> collect(PartialFunction<? super T,? extends R> partialFunction)
      Collects all elements that are in the domain of the given partialFunction by mapping the elements to type R.

      More specifically, for each of this elements in iteration order first it is checked

      
       partialFunction.isDefinedAt(element)
       
      If the elements makes it through that filter, the mapped instance is added to the result collection
      
       R newElement = partialFunction.apply(element)
       
      Note:If this Traversable is ordered (i.e. extends Ordered, the caller of collect has to ensure that the elements are comparable (i.e. extend Comparable).
      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 type R
      Throws:
      NullPointerException - if partialFunction is null
    • containsAll

      default boolean containsAll(Iterable<? extends T> elements)
      Tests if this Traversable contains all given elements.

      The result is equivalent to elements.isEmpty() ? true : contains(elements.head()) && containsAll(elements.tail()) but implemented without recursion.

      Parameters:
      elements - A List of values of type T.
      Returns:
      true, if this List contains all given elements, false otherwise.
      Throws:
      NullPointerException - if elements is null
    • count

      default int count(Predicate<? super T> predicate)
      Counts the elements which satisfy the given predicate.
      Parameters:
      predicate - A predicate
      Returns:
      A number >= 0
      Throws:
      NullPointerException - if predicate is null.
    • distinct

      Traversable<T> distinct()
      Returns a new version of this which contains no duplicates. Elements are compared using equals.
      Returns:
      a new Traversable containing this elements without duplicates
    • distinctBy

      Traversable<T> distinctBy(Comparator<? super T> comparator)
      Returns a new version of this which contains no duplicates. Elements are compared using the given comparator.
      Parameters:
      comparator - A comparator
      Returns:
      a new Traversable containing this elements without duplicates
      Throws:
      NullPointerException - if comparator is null.
    • distinctBy

      <U> Traversable<T> distinctBy(Function<? super T,? extends U> keyExtractor)
      Returns a new version of this which contains no duplicates. Elements mapped to keys which are compared using equals.

      The elements of the result are determined in the order of their occurrence - first match wins.

      Type Parameters:
      U - key type
      Parameters:
      keyExtractor - A key extractor
      Returns:
      a new Traversable containing this elements without duplicates
      Throws:
      NullPointerException - if keyExtractor is null
    • drop

      Traversable<T> drop(int n)
      Drops the first n elements of this or all elements, if this length < n.
      Parameters:
      n - The number of elements to drop.
      Returns:
      a new instance consisting of all elements of this except the first n ones, or else the empty instance, if this has less than n elements.
    • dropRight

      Traversable<T> dropRight(int n)
      Drops the last n elements of this or all elements, if this length < n.
      Parameters:
      n - The number of elements to drop.
      Returns:
      a new instance consisting of all elements of this except the last n ones, or else the empty instance, if this has less than n elements.
    • dropUntil

      Traversable<T> dropUntil(Predicate<? super T> predicate)
      Drops elements until the predicate holds for the current element.
      Parameters:
      predicate - A condition tested subsequently for this elements.
      Returns:
      a new instance consisting of all elements starting from the first one which does satisfy the given predicate.
      Throws:
      NullPointerException - if predicate is null
    • dropWhile

      Traversable<T> dropWhile(Predicate<? super T> predicate)
      Drops elements while the predicate holds for the current element.

      Note: This is essentially the same as dropUntil(predicate.negate()). It is intended to be used with method references, which cannot be negated directly.

      Parameters:
      predicate - A condition tested subsequently for this elements.
      Returns:
      a new instance consisting of all elements starting from the first one which does not satisfy the given predicate.
      Throws:
      NullPointerException - if predicate is null
    • equals

      boolean equals(Object obj)
      In Vavr there are four basic classes of collections:
      • Seq (sequential elements)
      • Set (distinct elements)
      • Map (indexed elements)
      • Multimap (indexed collections)
      Two collection instances of these classes are equal if and only if both collections
      • belong to the same basic collection class (Seq, Set, Map or Multimap)
      • contain the same elements
      • have the same element order, if the collections are of type Seq
      Two Map/Multimap elements, resp. entries, (key1, value1) and (key2, value2) are equal, if the keys are equal and the values are equal.

      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.
      Specified by:
      equals in interface Value<T>
      Overrides:
      equals in class Object
      Parameters:
      obj - an object, may be null
      Returns:
      true, if this collection equals the given object according to the rules described above, false otherwise.
    • existsUnique

      default boolean existsUnique(Predicate<? super T> predicate)
      Checks, if a unique elements exists such that the predicate holds.
      Parameters:
      predicate - A Predicate
      Returns:
      true, if predicate holds for a unique element, false otherwise
      Throws:
      NullPointerException - if predicate is null
    • filter

      Traversable<T> filter(Predicate<? super T> predicate)
      Returns a new traversable consisting of all elements which satisfy the given predicate.
      Parameters:
      predicate - A predicate
      Returns:
      a new traversable
      Throws:
      NullPointerException - if predicate is null
    • reject

      default Traversable<T> reject(Predicate<? super T> predicate)
      Returns a new traversable consisting of all elements which do not satisfy the given predicate.

      The default implementation is equivalent to

      filter(predicate.negate()
      Parameters:
      predicate - A predicate
      Returns:
      a new traversable
      Throws:
      NullPointerException - if predicate is null
    • find

      default Option<T> find(Predicate<? super T> predicate)
      Returns the first element of this which satisfies the given predicate.
      Parameters:
      predicate - A predicate.
      Returns:
      Some(element) or None, where element may be null (i.e. List.of(null).find(e -> e == null)).
      Throws:
      NullPointerException - if predicate is null
    • findLast

      default Option<T> findLast(Predicate<? super T> predicate)
      Returns the last element of this which satisfies the given predicate.

      Same as reverse().find(predicate).

      Parameters:
      predicate - A predicate.
      Returns:
      Some(element) or None, where element may be null (i.e. List.of(null).find(e -> e == null)).
      Throws:
      NullPointerException - if predicate is null
    • flatMap

      <U> Traversable<U> flatMap(Function<? super T,? extends Iterable<? extends U>> mapper)
      FlatMaps this Traversable.
      Type Parameters:
      U - The resulting component type.
      Parameters:
      mapper - A mapper
      Returns:
      A new Traversable instance.
    • foldLeft

      default <U> U foldLeft(U zero, BiFunction<? super U,? super T,? extends U> f)
      Description copied from interface: Foldable
      Folds this elements from the left, starting with zero and successively calling combine.

      Example:

       
       // = "cba!"
       List("a", "b", "c").foldLeft("!", (xs, x) -> x + xs)
        
      Specified by:
      foldLeft in interface Foldable<T>
      Type Parameters:
      U - the type to fold over
      Parameters:
      zero - A zero element to start with.
      f - A function which combines elements.
      Returns:
      a folded value
    • foldRight

      <U> U foldRight(U zero, BiFunction<? super T,? super U,? extends U> f)
      Description copied from interface: Foldable
      Folds this elements from the right, starting with zero and successively calling combine.

      Example:

       
       // = "!cba"
       List("a", "b", "c").foldRight("!", (x, xs) -> xs + x)
        
      Specified by:
      foldRight in interface Foldable<T>
      Type Parameters:
      U - the type of the folded value
      Parameters:
      zero - A zero element to start with.
      f - A function which combines elements.
      Returns:
      a folded value
    • forEachWithIndex

      default void forEachWithIndex(ObjIntConsumer<? super T> action)
      Performs an action on each element. In contrast to Value.forEach(Consumer), additionally the element's index is passed to the given action.

      This is essentially the same as iterator().zipWithIndex().forEach() but performs better because no intermediate Tuple2 instances are created and no boxing of int values takes place.

      Please note that subsequent calls to forEachWithIndex might lead to different iteration orders, depending on the underlying Traversable implementation.

      Please also note that forEachWithIndex might loop infinitely if the Traversable is lazily evaluated, like Stream.

      Parameters:
      action - A ObjIntConsumer
      Throws:
      NullPointerException - if action is null
    • get

      default T get()
      Gets the first value in iteration order if this Traversable is not empty, otherwise throws.
      Specified by:
      get in interface Value<T>
      Returns:
      the first value
      Throws:
      NoSuchElementException - if this Traversable is empty.
    • groupBy

      <C> Map<C,? extends Traversable<T>> groupBy(Function<? super T,? extends C> classifier)
      Groups this elements by classifying the elements.
      Type Parameters:
      C - classified class type
      Parameters:
      classifier - A function which classifies elements into classes
      Returns:
      A Map containing the grouped elements
      Throws:
      NullPointerException - if classifier is null.
      See Also:
    • grouped

      Iterator<? extends Traversable<T>> grouped(int size)
      Groups this Traversable into fixed size blocks.

      Let length be the length of this Iterable. Then grouped is defined as follows:

      • If this.isEmpty(), the resulting Iterator is empty.
      • If size <= length, the resulting Iterator will contain length / size blocks of size size and maybe a non-empty block of size length % size, if there are remaining elements.
      • If size > length, the resulting Iterator will contain one block of size length.
      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]]
       
       
      Please note that grouped(int) is a special case of sliding(int, int), i.e. grouped(size) is the same as sliding(size, size).
      Parameters:
      size - a positive block size
      Returns:
      A new Iterator of grouped blocks of the given size
      Throws:
      IllegalArgumentException - if size is negative or zero
    • hasDefiniteSize

      boolean hasDefiniteSize()
      Checks if this Traversable is known to have a finite size.

      This method should be implemented by classes only, i.e. not by interfaces.

      Returns:
      true, if this Traversable is known to have a finite size, false otherwise.
    • head

      T head()
      Returns the first element of a non-empty Traversable.
      Returns:
      The first element of this Traversable.
      Throws:
      NoSuchElementException - if this is empty
    • headOption

      default Option<T> headOption()
      Returns the first element of a non-empty Traversable as Option.
      Returns:
      Some(element) or None if this is empty.
    • hashCode

      int hashCode()
      Returns the hash code of this collection.
      We distinguish between two types of hashes, those for collections with predictable iteration order (like Seq) and those with arbitrary iteration order (like Set, Map and Multimap).
      In all cases the hash of an empty collection is defined to be 1.
      Collections with predictable iteration order are hashed as follows:
      
       int hash = 1;
       for (T t : this) { hash = hash * 31 + Objects.hashCode(t); }
       
      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 += Objects.hashCode(t); }
       
      Please note that the particular hashing algorithms may change in a future version of Vavr.
      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;
           }
      
           &#64;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;
               }
           }
      
           &#64;Override
           public int hashCode() {
               return hashCode.get();
           }
      
           &#64;Override
           public String toString() {
               return "Hashed(" + (key == null ? "null" : key.toString()) + ")";
           }
       }
      Specified by:
      hashCode in interface Value<T>
      Overrides:
      hashCode in class Object
      Returns:
      The hash code of this collection
    • init

      Traversable<T> init()
      Dual of tail(), returning all elements except the last.
      Returns:
      a new instance containing all elements except the last.
      Throws:
      UnsupportedOperationException - if this is empty
    • initOption

      default Option<? extends Traversable<T>> initOption()
      Dual of tailOption(), returning all elements except the last as Option.
      Returns:
      Some(traversable) or None if this is empty.
    • isDistinct

      default boolean isDistinct()
      Checks if this Traversable may consist of distinct elements only.
      Returns:
      true if this Traversable may consist of distinct elements only, false otherwise.
    • isEmpty

      default boolean isEmpty()
      Checks if this Traversable is empty.
      Specified by:
      isEmpty in interface Value<T>
      Returns:
      true, if this Traversable contains no elements, false otherwise.
    • isOrdered

      default boolean isOrdered()
      Checks if this Traversable is ordered
      Returns:
      true, if this Traversable is ordered, false otherwise.
    • isSequential

      default boolean isSequential()
      Checks if the elements of this Traversable appear in encounter order.
      Returns:
      true, if the insertion order of elements is preserved, false otherwise.
    • isSingleValued

      default boolean isSingleValued()
      Each of Vavr's collections may contain more than one element.
      Specified by:
      isSingleValued in interface Value<T>
      Returns:
      false
    • isTraversableAgain

      boolean isTraversableAgain()
      Checks if this Traversable can be repeatedly traversed.

      This method should be implemented by classes only, i.e. not by interfaces.

      Returns:
      true, if this Traversable is known to be traversable repeatedly, false otherwise.
    • iterator

      default Iterator<T> iterator()
      An iterator by means of head() and tail(). Subclasses may want to override this method.
      Specified by:
      iterator in interface Iterable<T>
      Specified by:
      iterator in interface Value<T>
      Returns:
      A new Iterator of this Traversable elements.
    • last

      T last()
      Dual of head(), returning the last element.
      Returns:
      the last element.
      Throws:
      NoSuchElementException - is this is empty
    • lastOption

      default Option<T> lastOption()
      Dual of headOption(), returning the last element as Option.
      Returns:
      Some(element) or None if this is empty.
    • length

      int length()
      Computes the number of elements of this Traversable.

      Same as size().

      Returns:
      the number of elements
    • map

      <U> Traversable<U> map(Function<? super T,? extends U> mapper)
      Maps the elements of this Traversable to elements of a new type preserving their order, if any.
      Specified by:
      map in interface Value<T>
      Type Parameters:
      U - Component type of the target Traversable
      Parameters:
      mapper - A mapper.
      Returns:
      a mapped Traversable
      Throws:
      NullPointerException - if mapper is null
    • max

      default Option<T> max()
      Calculates the maximum of this elements according to their natural order. Especially the underlying order of sorted collections is not taken into account.

      Examples:

       
       List.empty().max()             // = None
       List.of(1, 2, 3).max()         // = Some(3)
       List.of("a", "b", "c").max()   // = Some("c")
       List.of(1.0, Double.NaN).max() // = NaN
       List.of(1, "a").max()          // throws
       
       
      Returns:
      Some(maximum) of this elements or None if this is empty
      Throws:
      NullPointerException - if an element is null
      ClassCastException - if the elements do not have a natural order, i.e. they do not implement Comparable
    • maxBy

      default Option<T> maxBy(Comparator<? super T> comparator)
      Calculates the maximum of this elements using a specific comparator.
      Parameters:
      comparator - A non-null element comparator
      Returns:
      Some(maximum) of this elements or None if this is empty
      Throws:
      NullPointerException - if comparator is null
    • maxBy

      default <U extends Comparable<? super U>> Option<T> maxBy(Function<? super T,? extends U> f)
      Calculates the maximum of this elements within the co-domain of a specific function.
      Type Parameters:
      U - The type where elements are compared
      Parameters:
      f - A function that maps this elements to comparable elements
      Returns:
      The element of type T which is the maximum within U
      Throws:
      NullPointerException - if f is null.
    • min

      default Option<T> min()
      Calculates the minimum of this elements according to their natural order in O(n). Especially the underlying order of sorted collections is not taken into account.

      Examples:

       
       List.empty().min()             // = None
       List.of(1, 2, 3).min()         // = Some(1)
       List.of("a", "b", "c").min()   // = Some("a")
       List.of(1.0, Double.NaN).min() // = NaN
       List.of(1, "a").min()          // throws
       
       
      There is an exception for Double and Float: The minimum is defined to be NaN if this contains NaN. According to the natural order NaN would be the maximum element instead.
      Returns:
      Some(minimum) of this elements or None if this is empty
      Throws:
      NullPointerException - if an element is null
      ClassCastException - if the elements do not have a natural order, i.e. they do not implement Comparable
    • minBy

      default Option<T> minBy(Comparator<? super T> comparator)
      Calculates the minimum of this elements using a specific comparator.
      Parameters:
      comparator - A non-null element comparator
      Returns:
      Some(minimum) of this elements or None if this is empty
      Throws:
      NullPointerException - if comparator is null
    • minBy

      default <U extends Comparable<? super U>> Option<T> minBy(Function<? super T,? extends U> f)
      Calculates the minimum of this elements within the co-domain of a specific function.
      Type Parameters:
      U - The type where elements are compared
      Parameters:
      f - A function that maps this elements to comparable elements
      Returns:
      The element of type T which is the minimum within U
      Throws:
      NullPointerException - if f is null.
    • mkCharSeq

      default CharSeq mkCharSeq()
      Joins the elements of this by concatenating their string representations.

      This has the same effect as calling mkCharSeq("", "", "").

      Returns:
      a new CharSeq
    • mkCharSeq

      default CharSeq mkCharSeq(CharSequence delimiter)
      Joins the string representations of this elements using a specific delimiter.

      This has the same effect as calling mkCharSeq("", delimiter, "").

      Parameters:
      delimiter - A delimiter string put between string representations of elements of this
      Returns:
      A new CharSeq
    • mkCharSeq

      default CharSeq mkCharSeq(CharSequence prefix, CharSequence delimiter, CharSequence suffix)
      Joins the string representations of this elements using a specific delimiter, prefix and suffix.

      Example: List.of("a", "b", "c").mkCharSeq("Chars(", ", ", ")") = CharSeq.of("Chars(a, b, c))"

      Parameters:
      prefix - prefix of the resulting CharSeq
      delimiter - A delimiter string put between string representations of elements of this
      suffix - suffix of the resulting CharSeq
      Returns:
      a new CharSeq
    • mkString

      default String mkString()
      Joins the elements of this by concatenating their string representations.

      This has the same effect as calling mkString("", "", "").

      Returns:
      a new String
    • mkString

      default String mkString(CharSequence delimiter)
      Joins the string representations of this elements using a specific delimiter.

      This has the same effect as calling mkString("", delimiter, "").

      Parameters:
      delimiter - A delimiter string put between string representations of elements of this
      Returns:
      A new String
    • mkString

      default String mkString(CharSequence prefix, CharSequence delimiter, CharSequence suffix)
      Joins the string representations of this elements using a specific delimiter, prefix and suffix.

      Example: List.of("a", "b", "c").mkString("Chars(", ", ", ")") = "Chars(a, b, c)"

      Parameters:
      prefix - prefix of the resulting string
      delimiter - A delimiter string put between string representations of elements of this
      suffix - suffix of the resulting string
      Returns:
      a new String
    • nonEmpty

      default boolean nonEmpty()
      Checks, this Traversable is not empty.

      The call is equivalent to !isEmpty().

      Returns:
      true, if an underlying value is present, false otherwise.
    • orElse

      Traversable<T> orElse(Iterable<? extends T> other)
      Returns this Traversable if it is nonempty, otherwise return the alternative.
      Parameters:
      other - An alternative Traversable
      Returns:
      this Traversable if it is nonempty, otherwise return the alternative.
    • orElse

      Traversable<T> orElse(Supplier<? extends Iterable<? extends T>> supplier)
      Returns this Traversable if it is nonempty, otherwise return the result of evaluating supplier.
      Parameters:
      supplier - An alternative Traversable supplier
      Returns:
      this Traversable if it is nonempty, otherwise return the result of evaluating supplier.
    • partition

      Tuple2<? extends Traversable<T>,? extends Traversable<T>> partition(Predicate<? super T> predicate)
      Creates a partition of this Traversable by splitting this elements in two in distinct traversables according to a predicate.
      Parameters:
      predicate - A predicate which classifies an element if it is in the first or the second traversable.
      Returns:
      A disjoint union of two traversables. The first Traversable contains all elements that satisfy the given predicate, the second Traversable contains all elements that don't. The original order of elements is preserved.
      Throws:
      NullPointerException - if predicate is null
    • peek

      Traversable<T> peek(Consumer<? super T> action)
      Description copied from interface: Value
      Performs the given action on the first element if this is an eager implementation. Performs the given action on all elements (the first immediately, successive deferred), if this is a lazy implementation.
      Specified by:
      peek in interface Value<T>
      Parameters:
      action - The action that will be performed on the element(s).
      Returns:
      this instance
    • product

      default Number product()
      Calculates the product of this elements. Supported component types are Byte, Double, Float, Integer, Long, Short, BigInteger and BigDecimal.

      Examples:

       
       List.empty().product()              // = 1
       List.of(1, 2, 3).product()          // = 6L
       List.of(0.1, 0.2, 0.3).product()    // = 0.006
       List.of("apple", "pear").product()  // throws
       
       
      Please also see Foldable.fold(Object, BiFunction), a way to do a type-safe multiplication of elements.
      Returns:
      a Number representing the sum of this elements
      Throws:
      UnsupportedOperationException - if this elements are not numeric
    • reduceLeft

      default T reduceLeft(BiFunction<? super T,? super T,? extends T> op)
      Accumulates the elements of this Traversable by successively calling the given operation op from the left.
      Specified by:
      reduceLeft in interface Foldable<T>
      Parameters:
      op - A BiFunction of type T
      Returns:
      the reduced value.
      Throws:
      NoSuchElementException - if this is empty
      NullPointerException - if op is null
    • reduceLeftOption

      default Option<T> reduceLeftOption(BiFunction<? super T,? super T,? extends T> op)
      Shortcut for isEmpty() ? Option.none() : Option.some(reduceLeft(op)).
      Specified by:
      reduceLeftOption in interface Foldable<T>
      Parameters:
      op - A BiFunction of type T
      Returns:
      a reduced value
      Throws:
      NullPointerException - if op is null
    • reduceRight

      default T reduceRight(BiFunction<? super T,? super T,? extends T> op)
      Accumulates the elements of this Traversable by successively calling the given operation op from the right.
      Specified by:
      reduceRight in interface Foldable<T>
      Parameters:
      op - An operation of type T
      Returns:
      the reduced value.
      Throws:
      NoSuchElementException - if this is empty
      NullPointerException - if op is null
    • reduceRightOption

      default Option<T> reduceRightOption(BiFunction<? super T,? super T,? extends T> op)
      Shortcut for isEmpty() ? Option.none() : Option.some(reduceRight(op)).
      Specified by:
      reduceRightOption in interface Foldable<T>
      Parameters:
      op - An operation of type T
      Returns:
      a reduced value
      Throws:
      NullPointerException - if op is null
    • replace

      Traversable<T> replace(T currentElement, T newElement)
      Replaces the first occurrence (if exists) of the given currentElement with newElement.
      Parameters:
      currentElement - An element to be substituted.
      newElement - A replacement for currentElement.
      Returns:
      a Traversable containing all elements of this where the first occurrence of currentElement is replaced with newElement.
    • replaceAll

      Traversable<T> replaceAll(T currentElement, T newElement)
      Replaces all occurrences of the given currentElement with newElement.
      Parameters:
      currentElement - An element to be substituted.
      newElement - A replacement for currentElement.
      Returns:
      a Traversable containing all elements of this where all occurrences of currentElement are replaced with newElement.
    • retainAll

      Traversable<T> retainAll(Iterable<? extends T> elements)
      Keeps all occurrences of the given elements from this.
      Parameters:
      elements - Elements to be kept.
      Returns:
      a Traversable containing all occurrences of the given elements.
      Throws:
      NullPointerException - if elements is null
    • scan

      Traversable<T> scan(T zero, BiFunction<? super T,? super T,? extends T> operation)
      Computes a prefix scan of the elements of the collection. Note: The neutral element z may be applied more than once.
      Parameters:
      zero - neutral element for the operator op
      operation - the associative operator for the scan
      Returns:
      a new traversable collection containing the prefix scan of the elements in this traversable collection
      Throws:
      NullPointerException - if operation is null.
    • scanLeft

      <U> Traversable<U> scanLeft(U zero, BiFunction<? super U,? super T,? extends U> operation)
      Produces a collection containing cumulative results of applying the operator going left to right. Note: will not terminate for infinite-sized collections. Note: might return different results for different runs, unless the underlying collection type is ordered.
      Type Parameters:
      U - the type of the elements in the resulting collection
      Parameters:
      zero - the initial value
      operation - the binary operator applied to the intermediate result and the element
      Returns:
      collection with intermediate results
      Throws:
      NullPointerException - if operation is null.
    • scanRight

      <U> Traversable<U> scanRight(U zero, BiFunction<? super T,? super U,? extends U> operation)
      Produces a collection containing cumulative results of applying the operator going right to left. The head of the collection is the last cumulative result. Note: will not terminate for infinite-sized collections. Note: might return different results for different runs, unless the underlying collection type is ordered.
      Type Parameters:
      U - the type of the elements in the resulting collection
      Parameters:
      zero - the initial value
      operation - the binary operator applied to the intermediate result and the element
      Returns:
      collection with intermediate results
      Throws:
      NullPointerException - if operation is null.
    • single

      default T single()
      Returns the single element of this Traversable or throws, if this is empty or contains more than one element.
      Returns:
      the single element from the Traversable
      Throws:
      NoSuchElementException - if the Traversable does not contain a single element.
    • singleOption

      default Option<T> singleOption()
      Returns the only element of a Traversable as Option.
      Returns:
      Some(element) or None if the Traversable does not contain a single element.
    • size

      default int size()
      Computes the number of elements of this Traversable.

      Same as length().

      Returns:
      the number of elements
    • slideBy

      Iterator<? extends Traversable<T>> slideBy(Function<? super T,?> classifier)
      Slides a non-overlapping window of a variable size over this Traversable.

      Each window contains elements with the same class, as determined by classifier. Two consecutive values in this Traversable will be in the same window only if classifier returns equal values for them. Otherwise, the values will constitute the last element of the previous window and the first element of the next window.

      Examples:

      
       [].slideBy(Function.identity()) = []
       [1,2,3,4,4,5].slideBy(Function.identity()) = [[1],[2],[3],[4,4],[5]]
       [1,2,3,10,12,5,7,20,29].slideBy(x -> x/10) = [[1,2,3],[10,12],[5,7],[20,29]]
       
      Parameters:
      classifier - A function which classifies elements into classes
      Returns:
      A new Iterator of windows of the grouped elements
      Throws:
      NullPointerException - if classifier is null.
    • sliding

      Iterator<? extends Traversable<T>> sliding(int size)
      Slides a window of a specific size and step size 1 over this Traversable by calling sliding(int, int).
      Parameters:
      size - a positive window size
      Returns:
      a new Iterator of windows of a specific size using step size 1
      Throws:
      IllegalArgumentException - if size is negative or zero
    • sliding

      Iterator<? extends Traversable<T>> sliding(int size, int step)
      Slides a window of a specific size and step size over this Traversable.

      Examples:

       
       [].sliding(1,1) = []
       [1,2,3,4,5].sliding(2,3) = [[1,2],[4,5]]
       [1,2,3,4,5].sliding(2,4) = [[1,2],[5]]
       [1,2,3,4,5].sliding(2,5) = [[1,2]]
       [1,2,3,4].sliding(5,3) = [[1,2,3,4],[4]]
       
       
      Parameters:
      size - a positive window size
      step - a positive step size
      Returns:
      a new Iterator of windows of a specific size using a specific step size
      Throws:
      IllegalArgumentException - if size or step are negative or zero
    • span

      Tuple2<? extends Traversable<T>,? extends Traversable<T>> span(Predicate<? super T> predicate)
      Returns a tuple where the first element is the longest prefix of elements that satisfy the given predicate and the second element is the remainder.
      Parameters:
      predicate - A predicate.
      Returns:
      a Tuple containing the longest prefix of elements that satisfy p and the remainder.
      Throws:
      NullPointerException - if predicate is null
    • spliterator

      default Spliterator<T> spliterator()
      Specified by:
      spliterator in interface Iterable<T>
      Specified by:
      spliterator in interface Value<T>
    • sum

      default Number sum()
      Calculates the sum of this elements. Supported component types are Byte, Double, Float, Integer, Long, Short, BigInteger and BigDecimal.

      Examples:

       
       List.empty().sum()              // = 0
       List.of(1, 2, 3).sum()          // = 6L
       List.of(0.1, 0.2, 0.3).sum()    // = 0.6
       List.of("apple", "pear").sum()  // throws
       
       
      Please also see Foldable.fold(Object, BiFunction), a way to do a type-safe summation of elements.
      Returns:
      a Number representing the sum of this elements
      Throws:
      UnsupportedOperationException - if this elements are not numeric
    • tail

      Traversable<T> tail()
      Drops the first element of a non-empty Traversable.
      Returns:
      A new instance of Traversable containing all elements except the first.
      Throws:
      UnsupportedOperationException - if this is empty
    • tailOption

      Option<? extends Traversable<T>> tailOption()
      Drops the first element of a non-empty Traversable and returns an Option.
      Returns:
      Some(traversable) or None if this is empty.
    • take

      Traversable<T> take(int n)
      Takes the first n elements of this or all elements, if this length < n.

      The result is equivalent to sublist(0, max(0, min(length(), n))) but does not throw if n < 0 or n > length().

      In the case of n < 0 the empty instance is returned, in the case of n > length() this is returned.

      Parameters:
      n - The number of elements to take.
      Returns:
      A new instance consisting of the first n elements of this or all elements, if this has less than n elements.
    • takeRight

      Traversable<T> takeRight(int n)
      Takes the last n elements of this or all elements, if this length < n.

      The result is equivalent to sublist(max(0, min(length(), length() - n)), n), i.e. takeRight will not throw if n < 0 or n > length().

      In the case of n < 0 the empty instance is returned, in the case of n > length() this is returned.

      Parameters:
      n - The number of elements to take.
      Returns:
      A new instance consisting of the last n elements of this or all elements, if this has less than n elements.
    • takeUntil

      Traversable<T> takeUntil(Predicate<? super T> predicate)
      Takes elements until the predicate holds for the current element.

      Note: This is essentially the same as takeWhile(predicate.negate()). It is intended to be used with method references, which cannot be negated directly.

      Parameters:
      predicate - A condition tested subsequently for this elements.
      Returns:
      a new instance consisting of all elements before the first one which does satisfy the given predicate.
      Throws:
      NullPointerException - if predicate is null
    • takeWhile

      Traversable<T> takeWhile(Predicate<? super T> predicate)
      Takes elements while the predicate holds for the current element.
      Parameters:
      predicate - A condition tested subsequently for the contained elements.
      Returns:
      a new instance consisting of all elements before the first one which does not satisfy the given predicate.
      Throws:
      NullPointerException - if predicate is null
    • unzip

      <T1, T2> Tuple2<? extends Traversable<T1>,? extends Traversable<T2>> unzip(Function<? super T,Tuple2<? extends T1,? extends T2>> unzipper)
      Unzips this elements by mapping this elements to pairs which are subsequently split into two distinct sets.
      Type Parameters:
      T1 - 1st element type of a pair returned by unzipper
      T2 - 2nd element type of a pair returned by unzipper
      Parameters:
      unzipper - a function which converts elements of this to pairs
      Returns:
      A pair of set containing elements split by unzipper
      Throws:
      NullPointerException - if unzipper is null
    • unzip3

      <T1, T2, T3> Tuple3<? extends Traversable<T1>,? extends Traversable<T2>,? extends Traversable<T3>> unzip3(Function<? super T,Tuple3<? extends T1,? extends T2,? extends T3>> unzipper)
      Unzips this elements by mapping this elements to triples which are subsequently split into three distinct sets.
      Type Parameters:
      T1 - 1st element type of a triplet returned by unzipper
      T2 - 2nd element type of a triplet returned by unzipper
      T3 - 3rd element type of a triplet returned by unzipper
      Parameters:
      unzipper - a function which converts elements of this to pairs
      Returns:
      A triplet of set containing elements split by unzipper
      Throws:
      NullPointerException - if unzipper is null
    • zip

      <U> Traversable<Tuple2<T,U>> zip(Iterable<? extends U> that)
      Returns a traversable formed from this traversable and another Iterable collection by combining corresponding elements in pairs. If one of the two iterables is longer than the other, its remaining elements are ignored.

      The length of the returned traversable is the minimum of the lengths of this traversable and that iterable.

      Type Parameters:
      U - The type of the second half of the returned pairs.
      Parameters:
      that - The Iterable providing the second half of each result pair.
      Returns:
      a new traversable containing pairs consisting of corresponding elements of this traversable and that iterable.
      Throws:
      NullPointerException - if that is null
    • zipAll

      <U> Traversable<Tuple2<T,U>> zipAll(Iterable<? extends U> that, T thisElem, U thatElem)
      Returns a traversable formed from this traversable and another Iterable by combining corresponding elements in pairs. If one of the two collections is shorter than the other, placeholder elements are used to extend the shorter collection to the length of the longer.

      The length of the returned traversable is the maximum of the lengths of this traversable and that iterable.

      Special case: if this traversable is shorter than that elements, and that elements contains duplicates, the resulting traversable may be shorter than the maximum of the lengths of this and that because a traversable contains an element at most once.

      If this Traversable is shorter than that, thisElem values are used to fill the result. If that is shorter than this Traversable, thatElem values are used to fill the result.

      Type Parameters:
      U - The type of the second half of the returned pairs.
      Parameters:
      that - The Iterable providing the second half of each result pair.
      thisElem - The element to be used to fill up the result if this traversable is shorter than that.
      thatElem - The element to be used to fill up the result if that is shorter than this traversable.
      Returns:
      A new traversable containing pairs consisting of corresponding elements of this traversable and that.
      Throws:
      NullPointerException - if that is null
    • zipWith

      <U, R> Traversable<R> zipWith(Iterable<? extends U> that, BiFunction<? super T,? super U,? extends R> mapper)
      Returns a traversable formed from this traversable and another Iterable collection by mapping elements. If one of the two iterables is longer than the other, its remaining elements are ignored.

      The length of the returned traversable is the minimum of the lengths of this traversable and that iterable.

      Type Parameters:
      U - The type of the second parameter of the mapper.
      R - The type of the mapped elements.
      Parameters:
      that - The Iterable providing the second parameter of the mapper.
      mapper - a mapper.
      Returns:
      a new traversable containing mapped elements of this traversable and that iterable.
      Throws:
      NullPointerException - if that or mapper is null
    • zipWithIndex

      Traversable<Tuple2<T,Integer>> zipWithIndex()
      Zips this traversable with its indices.
      Returns:
      A new traversable containing all elements of this traversable paired with their index, starting with 0.
    • zipWithIndex

      <U> Traversable<U> zipWithIndex(BiFunction<? super T,? super Integer,? extends U> mapper)
      Zips this traversable with its indices by applying mapper provided.
      Type Parameters:
      U - The type of the mapped elements.
      Parameters:
      mapper - a mapper.
      Returns:
      a new traversable containing elements of this traversable, zipped with indices, and mapped with mapper provided.
      Throws:
      NullPointerException - if mapper is null