
Let's just go straight to the example to see what this means. Returns a sequence formed from this sequence and another iterable collection by combining corresponding elements in pairs. Let's look at an example where we want to split a list into two lists where one contains the even numbers and the other one the odd numbers. Partitions this traversable collection in two traversable collections according to a predicate.Īs you may imagine, this can be very useful sometimes. Partition def partition(p: (A) ⇒ Boolean): (Traversable, Traversable) Given a list of tuples (language, released). Let's create a final example, where we use foldLeft to solve a problem we looked at in the previous post. fold however, doesn't guarantee the order of function executions. The main one is that foldLeft iterates the list from left to right, while foldRight iterates the list from right to left. However, there are differences between the operations. Starting with the start value, they iterate the elements of the collection using the function given as an argument to fold the collection. The first one is the accumulated value and the second is the value of the current element. They all take a start value and a function. These three operations are pretty similar. Return a list of all the elements until an element isn't less then 5.Įven takeWhile (x => x x x.map(x => x * x))įlatMap can give some rather surprising results, so make sure to read A collection of Scala flatMap examples by Alvin Alexander for more examples and ideas! Fold, FoldLeft, FoldRight Instead of having a static number of elements to return, we can now give a predicate to determine when to stop fetching elements.Įxample // Given an infinite recursive method creating a stream of even numbers. This operation takes the ideas from the take operation and gives it more flexibility. Takes the longest prefix of elements that satisfy a predicate. TakeWhile def takeWhile(p: (A) ⇒ Boolean): Traversable

Let’s start with a few operations that builds on ideas we've already looked at. In the final post of this series, we're going to continue to look at the variety of operations in the Scala Collection API.
