Jordi
Jordi

Reputation: 23247

Java: Function composition on stream

I need to create some code like this:

this.getPendingDocuments()
    .forEach((this::documentProcessed).andThen(this::createAuditory));

So I mean, I need to apply two functions to the same element.

Any ideas?

EDIT

Compiler tells me:

[Java] The target type of this expression must be a functional interface

enter image description here

Upvotes: 1

Views: 316

Answers (3)

fps
fps

Reputation: 34460

You must target your method references to a functional interface type. In this case, forEach requires a Consumer instance:

Consumer<Document> processDocument = this::documentProcessed;
this.getPendingDocuments().forEach(processDocument.andThen(this::createAuditory));

The code above uses Consumer.andThen to chain consumers. Of course, both methods should accept a Document instance as an argument (or whatever the type of the elements of the Iterable returned by the getPendingDocuments() method is).

Upvotes: 1

Nenad Vichentikj
Nenad Vichentikj

Reputation: 111

When you use forEach() you can add more functions inside... like this

this.getPendingDocuments()
.forEach( element -> {
     this.documentProcessed(element);
     this.createAuditory(element);
});

Upvotes: 2

Eran
Eran

Reputation: 393841

You can write a lambda expression that executes both methods:

this.getPendingDocuments()
    .forEach(doc -> {
                        this.documentProcessed(doc);
                        this.createAuditory(doc);
                    });

Upvotes: 3

Related Questions