I have scanned serveral links but didn't find an easy solution for Java 8 Lambda expression. The most useful hint I've found was on Java 8 Lambdas but did NOT really satisfy my interest.
I want to achieve a reoccuring pattern in my code:
List<?> content=retrieveContent(strFilter);
if (!content.isEmpty())
setField1(content.get(0));
and I would like to have it simple as
retrieveContent(strFilter, this::setField1) but somehow I don't get syntax properly - especially for the method. I can do it as a String and call if via method, but than its prone to typos... Any other ideas?
-
How do you know setField1() method is available?m0skit0– m0skit02017年03月02日 15:49:25 +00:00Commented Mar 2, 2017 at 15:49
1 Answer 1
It sounds like you're looking for a Consumer, which will work as long as you fill in the generics with a value other than <?>.
For example:
private List<Object> retrieveContent(String strFilter, Consumer<Object> firstItemConsumer) {
List<Object> list = new ArrayList<>();
// Build the return...
if(!list.isEmpty()) {
firstItemConsumer.accept(list.get(0));
}
return list;
}
Can then be called with:
List<Object> content = retrieveContent(strFilter, this::setField1);
2 Comments
<Object>, one could reference a type parameter of the host class, or a type parameter of the method if the method were made generic.