Splitting by Condition
For more complex splitting scenarios where you want to divide an array based on a certain condition for each element, you can use a combination of functional programming techniques:
- `filter`:This function creates a new array containing only elements that meet a specified predicate (condition).
- `partition`:This method splits an array into two sub-arrays based on a predicate. The first sub-array contains elements that satisfy the condition, while the second sub-array contains elements that don’t.
Example:
object Main {
def main(args: Array[String]) {
val numbers = Array(10, 5, 20, 15)
val evens = numbers.filter(_ % 2 == 0) // Filter even numbers
val odds = numbers.filter(_ % 2 != 0) // Filter odd numbers
// Alternatively, using partition
val (evenNumbers, oddNumbers) = numbers.partition(_ % 2 == 0)
println(evens.mkString(", ")) // Output: 10, 20
println(odds.mkString(", ")) // Output: 5, 15
}
}
How to split Array in Scala?
Arrays are a fundamental data structure in Scala, used to store collections of elements of the same type. Splitting an array involves dividing it into smaller sub-arrays based on specific criteria.
This article explores different methods for achieving this in Scala.
Table of Content
- 1. Using `splitAt`:
- 2. Using `slice` :
- 3. Splitting by Delimiter :
- 4. Splitting by Condition :
- Choosing the Right Method:
Contact Us