Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA 8 pass return value back into same method x number of times

I have this code which I want to refactor using a functional style, using Java 8. I would like to remove the mutable object currentRequest and still return the filtered request.

    HttpRequest currentRequest = httpRequest;
    for (Filter filter : filters) {
        currentRequest = filter.doFilter(currentRequest);
    }

The aim is to pass a request to the filter.doFilter method, and take the output and pass it back into the filter.doFilter method, and continue to do this until all filters are applied.

For example in a more convoluted way to the 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 composing functions, and the doFilter method should be a function like below:

    Function<HttpRequest, HttpRequest> applyFilter = request -> filters.get(0).doFilter(request);

But I know this is totally wrong, as I got stuck here.

The other way I was thinking was to use reduce, but I cannot see a way of using it in this case.

If you could help me out with a way of doing this, or point me to some resource that will be great.

like image 264
cani Avatar asked Jan 13 '18 12:01

cani


People also ask

Can a method return multiple times?

As per the Java Language Specification, the methods in Java can return only one value at a time. So returning multiple values from a method is theoretically not possible in Java.

How do you repeat a method in Java?

repeat() method is used to return String whose value is the concatenation of given String repeated count times. If the string is empty or the count is zero then the empty string is returned.

Can you return multiple times in Java?

You can return only one value in Java. If needed you can return multiple values using array or an object.

Can Java methods have multiple return values?

Java doesn't support multi-value returns.


1 Answers

It looks like you may want to do a reduce with your HttpRequest as its identity. Each step of the reduce will combine the intermediate result with the next filter, like so:

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

Note: the last function is used to merge two HttpRequests together if a parallel stream is used. If that's the route you wish to go down, then proceed with caution.

like image 91
Joe C Avatar answered Sep 28 '22 12:09

Joe C