You can use lambda instead of an anonymous class - and use the map to get the desired result + or Else 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 Function at all and it can rewrite the whole method as follows:
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 since findUnique can return null , you should use Optional.ofNullable() , not Optional.of() : the latter will throw an exception if the string is null .
And finally, I would add that it would be easier 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 signature of the method 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"))); }
source share