“Good” method to call method on each object using Stream API

后端 未结 3 1372
长情又很酷
长情又很酷 2021-02-12 06:14

Is it possible to run a method, in a consumer, like a method reference, but on the object passed to the consumer:

Arrays.stream(log.getHandlers()).forEach(h ->         


        
相关标签:
3条回答
  • 2021-02-12 06:34

    You don't need this. YourClassName::close will call the close method on the object passed to the consumer :

    Arrays.stream(log.getHandlers()).forEach(YourClassName::close);
    

    There are four kinds of method references (Source):

    Kind                                                                         Example
    ----                                                                         -------
    Reference to a static method                                                 ContainingClass::staticMethodName
    Reference to an instance method of a particular object                       containingObject::instanceMethodName
    Reference to an instance method of an arbitrary object of a particular type  ContainingType::methodName
    Reference to a constructor                                                   ClassName::new
    

    In your case, you need the third kind.

    0 讨论(0)
  • 2021-02-12 06:47

    I suppose it should be:

    Arrays.stream(log.getHandlers()).forEach(Handler::close);
    

    Provided the log.getHandlers() returns an array of objects of type Handler.

    0 讨论(0)
  • 2021-02-12 06:48

    Sure, but you must use the correct syntax of method reference, i.e. pass the class to which the close() method belong:

    Arrays.stream(log.getHandlers()).forEach(Handler::close);
    
    0 讨论(0)
提交回复
热议问题