Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 256
Lasse Frandsen Avatar asked Mar 08 '19 09:03

Lasse Frandsen


1 Answers

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

like image 170
senjin.hajrulahovic Avatar answered Nov 16 '22 00:11

senjin.hajrulahovic