My knowledge about list operations is from scripting languages. So in Java I stopped on something strange in case of finding cookie with particular name.
List<Cookie> cookies = Arrays.asList(request.getCookies());
String auth = cookies.stream()
.filter(c -> c.getName().equals("auth"))
.map(Cookie::getValue);
On the map
method IntelliJ is showing me "Cyclic inference".
Java compiler Error:(52, 25) java: incompatible types: no instance(s) of type variable(s) R exist so that java.util.stream.Stream conforms to java.lang.String
Your current code returns a Stream<String>
, so you need an extra step to return a string:
Optional<String> auth = cookies.stream()
.filter(c -> c.getName().equals("auth"))
.map(Cookie::getValue)
.findAny();
Note that it returns an Optional<String>
because there may be no Cookie that matches "auth". If you want to use a default if "auth" is not found you can use:
String auth = cookies.stream()
.filter(c -> c.getName().equals("auth"))
.map(Cookie::getValue)
.findAny().orElse("");
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