Java For Comprehension

Lasse Frandsen :

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?

senjin.hajrulahovic :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=69020&siteId=1