I've searched for solutions on how to get cookies by their name and all solutions point to using for-loops
and if
statements. See code below.
for (Cookie cookie : cookies) {
if (cookie.getName().equals("<NAME>")) {
// do something here
}
if (cookie.getName().equals("<ANOTHER_NAME>")) {
// do something here
}
// and so on...
}
Is there any simpler way to get the value by their name without having to do the loops and if's?
I need to make some "certain" processing for certain cookies I would want to retrieve Plus, I don't want to traverse through every cookie! There could be 10 or more and all I need is just three or something.
public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser.
The logic (as suggested by Matt Ball in the comments) would be:
// ...
Map<String, Cookie> cookieMap = new HashMap<>();
for (Cookie cookie : cookies) {
cookieMap.put(cookie.getName(), cookie);
}
Cookie firstRequiredCookie = cookieMap.get("<NAME>");
// do something with firstRequiredCookie
Cookie nextRequiredCookie = cookieMap.get("<ANOTHER_NAME>");
// do something with nextRequiredCookie
// ...
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