Understanding Java 8 Lambda Expressions

user3216798 :

I was reading this article on Java 8 and had the following questions/comments I would appreciate some feedback/response.

1) Is the @FunctionalInterface declaration necessary for the following code? Or could this same code be executed without it and it is for documentation purposes? It is unclear from whether it is necessary from the article.

@FunctionalInterface
private interface DTOSender {
   void send(String accountId, DTO dto);
}

void sendDTO(BisnessModel object, DTOSender dtoSender) {
   //some logic for sending...
   ...
   dtoSender.send(id, dto);
   ...
}

2) In general, can a function be passed as an argument to another function in Java 8? My understanding is only data types can be passed as arguments to functions, so I suppose it is not possible as a function is not a data type.

3) Do I need to do anything special to accomplish #2 above or can I just write my definitions of the 2 methods and just pass the one method as a parameter to the other method?

4) Can objects be passed as arguments to another function in Java 8? Do I need to do anything special to accomplish this or can I just write my definitions of the object and method and just pass the object as a parameter to the method?

Andronicus :
  1. @Functional Interface is just a hint, so that you don't put more methods into your interface.

  2. It can. Many methods on Stream take functions as parameter: Stream.of(1, 2, 3).forEach(System.out::println).

  3. Lambda is a function instance: Function<Integer, Integer> f = a -> a + 1. Edit: you can pass a function by name using method reference (see 2., println is a regular method).

  4. I don't fully get the question. If the method consumes any argument, that is not primitive, it takes an object (everything in java except for primitives is an object).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=409469&siteId=1