I have this code that I want to refactor using a functional style using Java 8. I would like to remove the currentRequest mutable object and still return the filtered request.
HttpRequest currentRequest = httpRequest; for (Filter filter : filters) { currentRequest = filter.doFilter(currentRequest); }
The goal is to pass a request to the filter.doFilter method and pass the result and pass it back to the filter.doFilter method and continue to do this until all filters are applied.
For example, in a more confusing way for a for loop
HttpRequest filteredRequest1 = filters.get(0).doFilter(currentRequest); HttpRequest filteredRequest2 = filters.get(1).doFilter(filteredRequest1); HttpRequest filteredRequest3 = filters.get(2).doFilter(filteredRequest2); ...
I think this is a case for compiling functions , and the doFilter method should be as shown below:
Function<HttpRequest, HttpRequest> applyFilter = request -> filters.get(0).doFilter(request);
But I know this is completely wrong as I am stuck here.
Another way, I thought, was to use reduce , but I see no way to use it in this case.
If you could help me do this, or point me to some resource that will be great.
source share