This question already has answers here:
How do I compare strings in Java?
                                
                                    (23个答案)
                                
                        
                                4年前关闭。
            
                    
我懂了。但是我的列表并不为空,它们具有代码为“ 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());


枚举链

public enum Chaines {

  ADPL("ADPL"),
  ADIL("ADIL"),
  ADSL("ADSL");

  private String code = "";

  Chaines(String code) {
    this.code = code;
  }

  public String getCode() {
    return this.code;
  }

}


这与CodeExecutionChaine相同

最佳答案

t -> t.getNomChaine() == Chaines.ADPL.getCode()更改为t -> t.equals(Chaines.ADPL.getCode())

==检查身份。因此,仅当两个引用指向同一对象时,==才会生成true。另一方面,equals检查equality。两个未指向同一对象但具有相似的properties的引用仍被视为相等。之所以得到NoSuchElementException,是因为您使用==来对filter进行Stream,这导致零个元素满足条件。

10-08 19:26