Scala concepts: Collect

assert("Hello World".collect {
  case character if Character.isUpperCase(character) => character.toLower
} == "hw")

assert("Hello World".filter(Character.isUpperCase).map(_.toLower) == "hw")

assert((1 to 10).collect {
  case num if num % 3 == 0 => "Fizz"
  case num if num % 5 == 0 => "Buzz"
}.toList == List("Fizz", "Buzz", "Fizz", "Fizz", "Buzz"))

assert(
  (1 to 10)
    .map { num =>
      if (num % 3 == 0) Some("Fizz")
      else if (num % 5 == 0) Some("Buzz")
      else None
    }
    .flatten
    .toList == List("Fizz", "Buzz", "Fizz", "Fizz", "Buzz")
)

Collect can be used on any collection, including Streaming collections like LazyList