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
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.
The lambda expressions can also be used to initialize arrays in Java.
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).
forEach((e) -> { System. out. print(e + ", "); }); Here, we are passing the lambda expression as an argument to ArrayList forEach().
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);
});
Arrays.stream(httpsServletRequest.getCookies())
.filter(cookie -> CookieSession.NAME.equals(cookie.getName()))
.forEach(cookie -> {
cookie.setValue(null);
cookie.setMaxAge(0);
cookie.setPath("/");
httpServletResponse.addCookie(cookie);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With