I am fixing some issue in a legacy module and came across this code which get the array of cookies from request object which can return null. The code looks for a specific cookie, if present then returns cookie value otherwise it returns null. Below is the existing code
final Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
final Cookie cookie = cookies[i];
if ("random cookie".equals(cookie.getName())) {
return cookie.getValue();
}
}
return null;
}
I refactored it to something like this
final Cookie[] cookies = request.getCookies();
if (cookies != null) {
Optional<Cookie> cookie = Arrays.stream(cookies).
filter(e -> "random cookie".equals(e.getName())).
findAny();
return cookie.isPresent() ? cookie.get().getValue() : null;
}
return null;
Can the above be refactored in a better way?