Search code examples
javascalaoption-type

Java For Comprehension


In Scala i can write a short method like this:

def xy(
  maybeX: Option[String],
  maybeY: Option[String]): Option[String] = {

  for {
    x <- maybeX
    y <- maybeY
  } yield {
    s"X: $x Y: $y"
  }
}

Does Java have something similar, when it comes to two or more Optional<> variables?


Solution

  • This would be the appropriate alternative:

    Optional<String> maybeXY = maybeX.flatMap(x -> maybeY.map(y -> x + y));
    

    The scala for comprehension is just syntactic sugar for map, flatMap and filter calls.

    Here's a good example: How to convert map/flatMap to for comprehension