简体   繁体   中英

Java Optional: how to do with long map() chain

Recently, I started using Optional when handling json response in our project:

Optional.ofNullable(root.get("a"))
        .map(a -> a.get("b"))
        .map(b -> b.get("c"))
        .map(c -> c.get("d"))

for each get(), I have to use a map() to keep the return value in the "safety box" which makes the code quite verbose. To access a very deep json field in a complex long json tree, it would end up with a quite long map() chain.

I was dreaming of something like this:

Optional.ofNullable(root.get("a")).map(a.get("b").get("c").get("d"))

If any of those get() methods returns a null value, I would get an empty Optional as result of the expression. Let's say, using one "safety box", all possible null values can be somehow handled and turned into empty Optional. Is it a silly thought?

Is there a way to make the code less-verbose?

Wrap it up inside a method:

static Optional<JsonObject> get(JsonObject root, String... paths) {
  Optional<JsonObject> opt = Optional.ofNullable(root);
  for (String p : paths) {
    if (!opt.isPresent()) break;
    opt = opt.map(a -> a.get(p));
  }
  return opt;
}

then call like:

Optional<JsonObject> jsonObject = get(root, "a", "b", "c", "d");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM