Java8 Optional with Function Chain Expression

I am wondering if there is a way to simplify the following code? I am trying to get something from a database using EBean. If there is something, then match it with the 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())); } 
+6
source share
1 answer

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"))); } 
+10
source

All Articles