Open In App

How to use partition in Scala?

'Partition' in Scala is a method used to split a collection a List or a tuple into separate collections, lists, or tuples based on a predicate function/method.

Usage:

Let's consider a simple example of the same.

Example 1:

object PartitionMethodExample1{
  def main(args: Array[String]): Unit = {
      val numberslist = List(1,2,3,4,5,6,7,8)
    
    //define a predicate function
    def isEvenNumber(n: Int): Boolean = n % 2 == 0
    
    //Use partition to split the list into separate collections
    val(evenNumbers, oddNumbers) = numberslist.partition(isEvenNumber)
    //Print the output
    println("Even Numbers: "+ evenNumbers)
    println("Odd Numbers: "+ oddNumbers)
  }
}


Explanation:

Output:

Screenshot-2024-03-17-012000

Example-1

Example 2:

object PartitionMethodExample2{
  def main(args: Array[String]){
      val words = Set("Channel", "Gucci", "Louis Vuitton", "Versace", "Adidas", "Allen Solly", "H&M", "Belanciaga", "Zara")
    
    //Define a predicate function to filter short words
    def isShortWord(word: String): Boolean = word.length <= 7
    
    //Use Partition to split the set into two collections.
    val(shortWords, longWords) = words.partition(isShortWord)
    
    //print the output of partition method
    println("Short Words: " + shortWords)
    println("Long Words: " + longWords)
  }
}

Explanation:

Output:

Screenshot-2024-03-17-144534

Example-2

Article Tags :