Reputation: 227
How can I write the following function using Java 8?
private static final Function<String, Integer> EmpIdToInt = (id) -> {
return Integer.valueOf(ACI.generate("emp",id).revealId().intValue());
};
Is there a better way of writing this function in Java 8?
Can anyone help?
Upvotes: 2
Views: 216
Reputation: 30676
Note: I take away private static final
for printing page.
IF your revealId
is an Integer you can simplified to :
Function<String, Integer> EmpIdToInt = id -> ACI.generate("emp",id).revealId();
OR when revealId
is not an Integer, but a int
will be auto-boxing to an Integer
, so you can remove the Integer.valueOf
method call:
Function<String, Integer> EmpIdToInt = id -> ACI.generate("emp",id)
.revealId().intValue();
OR you can using a curry
method chaining the functions step by step:
Note: class X
is where revealId
method is declared, and class Y
is where intValue
method is declared.
// revealId is an Integer
Function<String, Integer> EmpIdToInt = curry(ACI::generate, "emp")
.andThen(X::revealId);
// revealId is not an Integer
Function<String, Integer> EmpIdToInt = curry(ACI::generate, "emp")
.andThen(X::revealId)
.andThen(Y::intValue);
private static <T, A, R> Function<T, R> curry(BiFunction<A, T, R> it, A arg) {
return other -> it.apply(arg, other);
}
Upvotes: 2
Reputation: 56423
Is there a better way of writing this function in java 8??
you're already using the features of java 8 and yes you can make the code shorter by removing
(
)
because there is only one param and removing {
}
because there is only one statement of execution.
you could simplify it like so:
private static final Function<String, Integer> EmpIdToInt = id -> Integer.valueOf(ACI.generate("emp",id).revealId().intValue());
Upvotes: 3