2

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?

1
  • How do you know setField1() method is available? Commented Mar 2, 2017 at 15:49

1 Answer 1

6

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);
Sign up to request clarification or add additional context in comments.

2 Comments

And of course, instead of <Object>, one could reference a type parameter of the host class, or a type parameter of the method if the method were made generic.
Thx, this works basically the way as expected :-) Except that JPA does NOT like Lambda-stuff (at least for EclipseLink 2.5x)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.