Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 cyclic inference warning

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

like image 497
RobertW Avatar asked Oct 17 '14 09:10

RobertW


1 Answers

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("");
like image 176
assylias Avatar answered Sep 20 '22 14:09

assylias