Java 8 cyclic inference warning

2019-02-04 00:36发布

问题:

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

回答1:

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("");


回答2:

In essence, what this rather cryptic error message is saying is "the output of the stream sequence doesn't match what you are assigning it to in the end", ex:

String s = list.stream().map(s -> s); // this doesn't result in a String...

.findFirst().get() So to debug compilation, remove the assignment (temporarily), or, as the other answer says, add something that makes it return a String by collecting (ex: .collect(Collectors.joining(","))) or (getting like .findFirst().get()), or change the assignment, like Stream<String> stream = list.stream().map(...)