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?

Community
  • 1
  • 1
LeO
  • 4,238
  • 4
  • 48
  • 88

1 Answers1

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);
nickb
  • 59,313
  • 13
  • 108
  • 143
  • 1
    And of course, instead of ``, one could reference a type parameter of the host class, or a type parameter of the method if the method were made generic. – John Bollinger Mar 02 '17 at 15:53
  • Thx, this works basically the way as expected :-) Except that JPA does NOT like Lambda-stuff (at least for EclipseLink 2.5x) – LeO Mar 02 '17 at 16:22