Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 Optional with Function chaining expression [closed]

I am wondering is there a way to simplify the following code ? I am trying to get something from database by using EBean. If there's something then map it to an object or otherwise return the default implementation instance.

public static ObjectA test1() {

    Function<Optional<SqlRow>, ObjectA> sqlRowToObjectA= new Function<Optional<SqlRow>, ObjectA>() {
        @Override
        public AccountSummary apply(Optional<SqlRow> entry) {
            return entry.isPresent() ? new ObjectA(entry.get().getInt("id"), entry.get().getString("name"))
                 : ObjectA.EMPTY;
        }
    };

    return sqlRowToObjectA.apply(Optional.of(Ebean.createSqlQuery("select * from table1").findUnique()));
}
like image 403
peter Avatar asked Jan 21 '16 22:01

peter


1 Answers

You could use a lambda instead of an anonymous class - and use map to get the desired result + orElse for the default value:

Function<Optional<SqlRow>, ObjectA> sqlRowToObjectA =
    entry -> entry.map(e -> new ObjectA(e.getInt("id"), e.getString("name")))
                  .orElse(ObjectA.EMPTY);

However, in your example, you don't need a Function at all and could rewrite the whole method like this:

public static ObjectA test1() {
  SqlRow row = Ebean.createSqlQuery("select * from table1").findUnique();

  return Optional.ofNullable(row)
                 .map(e -> new ObjectA(e.getInt("id"), e.getString("name")))
                 .orElse(ObjectA.EMPTY);
}

Note that because findUnique may return null, you should use Optional.ofNullable() rather than Optional.of(): the latter will throw an exception if the row is null.


And finally, I would add that it would be simpler and more efficient to write:

public static ObjectA test1() {
  SqlRow row = Ebean.createSqlQuery("select * from table1").findUnique();

  return row == null ? ObjectA.EMPTY
                     : new ObjectA(row.getInt("id"), row.getString("name"));
}

or change the method signature and let the caller decide what to do if there is no result:

public static Optional<ObjectA> test1() {
  SqlRow row = Ebean.createSqlQuery("select * from table1").findUnique();

  return Optional.ofNullable(row)
                 .map(e -> new ObjectA(e.getInt("id"), e.getString("name")));
}
like image 59
assylias Avatar answered Oct 27 '22 01:10

assylias