JAVA 8 returns the return value back to the same method x number of times

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.

+5
source share
2 answers

It looks like you can do reduce with your HttpRequest as its identifier. Each reduction step combines the intermediate result with the following filter, for example:

 filters.stream().reduce(currentRequest, (req, filter) -> filter.doFilter(req), (req1, req2) -> throwAnExceptionAsWeShouldntBeHere()); 

Note. The latter function is used to combine two HttpRequests together if a parallel stream is used. If you want to go down this route, proceed with caution.

+3
source

Here's a method that passes filters and displays each one in a UnaryOperator<HttpRequest> . Then all functions are reduced through Function.andThen and finally, if the filters collections were not empty, the resulting linked function is executed using currentRequest as an argument:

 HttpRequest result = filters.stream() .map(filter -> ((Function<HttpRequest, HttpRequest>) filter::doFilter)) .reduce(Function::andThen) .map(function -> function.apply(currentRequest)) .orElse(currentRequest); 
+3
source

Source: https://habr.com/ru/post/1274678/


All Articles