Alexander Petrov Alexander Petrov - 1 year ago 98
Java Question

Chaining Consumers Java 8

Hello I am having the following problem. Lets say that We have object "Account" This object Account is immutable, so overtime we execute an action upon it we are actually transforming it to another state. For example Account can become ClosedAccount or NewAccount and so on. Now in some occasions my transitions are reflective Account is transformed to Account but something very small is changed like for example "modifiedDate". Because my Account is its essence immutable even the reflective operations are still creating new Accounts with updated values. If my object is not immutable I would have used something like :

List<String> accountsIds;>NewAccount)
.forEach(bla bla bla)

Now the problem is that the peek() will only change the state for mutable object. But in my case the Account is immutable so even if I create a new object this object will not be streamed further.

The question is is it possible to chain "Consumers" in such way that they work like "map" methods the output of the "Consumer" to become the input of the next "Consumer". In other words I am looking for "peek" operation that works on Immutable objects.

The reason I am asking this question is because my understanding is that "map" is a transformation operation, while I want to execute something that is more like an Action. It works as a transformation operation only because I am working with immutable objects but if I was using mutable objects it would have been just an action.

Answer Source

You are probably trying to solve a problem that does not exist. I think it is perfectly normal to do any change to an object with map() no matter how small the change is.

My understanding is that there is no semantic meaning behind operations like map() or peek(), and you can use either of them for any task where is suits.

peek() is often used for debugging: it allows you to log every item in the stream without using a terminal operation and destroying the stream. map() is used when you need to do something with objects and pass them forward.

Also, think about it: the method in the Consumer interface has one input parameter and it does not return any value. If your input parameter is immutable, it makes it impossible to return any value from this method without any duty tricks.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download