Java 8循环推理警告 [英] Java 8 cyclic inference warning
问题描述
我对列表操作的了解来自脚本语言。所以在Java中,我找到了一些奇怪的东西,以便找到具有特定名称的cookie。
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);
在地图
方法上,IntelliJ向我显示循环推理。
On the map
method IntelliJ is showing me "Cyclic inference".
Java编译器错误:(52,25)java:不兼容类型:没有类型变量的实例R存在于此java.util.stream.Stream符合java.lang.String
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
推荐答案
您当前的代码返回 Stream< 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();
请注意,它会返回可选< String>
因为可能没有与auth匹配的Cookie。如果你想使用默认值,如果找不到auth,你可以使用:
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("");
这篇关于Java 8循环推理警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!