java.util.NoSuchElementException:没有值存在 Java 8 Lambda
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31011091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.util.NoSuchElementException: No value present Java 8 Lambda
提问by Alexandre Picard-Lemieux
I got this. But my list is not empty and they have element with code "ADPL". Why this return me NoSuchElement ?
我懂了。但我的列表不是空的,他们有代码“ADPL”的元素。为什么这会返回给我 NoSuchElement ?
String retour = CodeExecutionChaine.A.getCode();
if (!lstChaines.isEmpty()) {
retour = lstChaines.stream()
.filter(t -> t.getNomChaine() == Chaines.ADPL.getCode())
.map(Chaine::getStatutChaine)
.findFirst()
.orElse(CodeExecutionChaine.A.getCode());
The enum Chaines
枚举链
public enum Chaines {
ADPL("ADPL"),
ADIL("ADIL"),
ADSL("ADSL");
private String code = "";
Chaines(String code) {
this.code = code;
}
public String getCode() {
return this.code;
}
}
This is the same for CodeExecutionChaine
这与 CodeExecutionChaine 相同
采纳答案by CKing
Change t -> t.getNomChaine() == Chaines.ADPL.getCode()
to t -> t.equals(Chaines.ADPL.getCode())
.
更改t -> t.getNomChaine() == Chaines.ADPL.getCode()
为t -> t.equals(Chaines.ADPL.getCode())
。
==
checks for identity. Therefore, ==
will result into true
only if two references point to the same object. On the other hand, equals
checks for equality
. Two references that don't point to the same object but have similar properties
are still considered equal. You get a NoSuchElementException
because you used ==
to filter
your Stream
which resulted in zero elements satisfying the condition.
==
检查身份。因此,只有当两个引用指向同一个对象时==
才会导致true
。另一方面,equals
检查equality
. 不指向同一个对象但具有相似对象的两个引用properties
仍然被认为是相等的。你得到了NoSuchElementException
,因为你使用==
到filter
你Stream
这就造成了满足条件的零个元素。