Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Array iteration to lambda expression

I have below code which iterates over Cookies to reset the cookie whose name matches CookieSession.NAME

  Cookie[] cookies = httpServletRequest.getCookies();
        LOGGER.info("Clearing cookies on welcome page");
        if (cookies != null)
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(CookieSession.NAME)) {                      
                cookie.setValue(null);
                cookie.setMaxAge(0);
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
              }
            }

can someone simplify it using java 8 lambda expression

like image 778
RanPaul Avatar asked Apr 08 '16 20:04

RanPaul


People also ask

How do you convert this method into a lambda expression?

To convert an anonymous method to a lambda expressionMove to the anonymous method you want to convert. From the Refactor menu of the VisualAid choose To Lambda. Telerik® JustCode™ will replace the anonymous method with a lambda expression.

Can you use lambda expression array?

The lambda expressions can also be used to initialize arrays in Java.

Is lambda expression faster than forEach?

Here I/O operation ( println ) is much slower than all possible overhead of calling lambda or creating an iterator. In general forEach might be slightly faster as it does everything inside the single method without creating the Iterator and calling hasNext and next (which is implicitly done by for-each loop).

What is the lambda expression to print all the elements of an array?

forEach((e) -> { System. out. print(e + ", "); }); Here, we are passing the lambda expression as an argument to ArrayList forEach().


2 Answers

Not sure if it will be simplified, but it can be done, yes:

Arrays.stream(cookies)
      .filter(c -> c.getName().equals(CookieSession.NAME))
      .forEach(cookie -> {
          cookie.setValue(null);
          cookie.setMaxAge(0);
          cookie.setPath("/");
          httpServletResponse.addCookie(cookie);
      });
like image 88
JB Nizet Avatar answered Oct 02 '22 01:10

JB Nizet


Arrays.stream(httpsServletRequest.getCookies())
    .filter(cookie -> CookieSession.NAME.equals(cookie.getName()))
    .forEach(cookie -> {
        cookie.setValue(null); 
        cookie.setMaxAge(0); 
        cookie.setPath("/");
        httpServletResponse.addCookie(cookie); 
    });
like image 34
Darth Android Avatar answered Oct 02 '22 03:10

Darth Android