3

I got this. But my list is not empty and they have element with code "ADPL". Why this return me 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

1 Answers1

3

Change t -> t.getNomChaine() == Chaines.ADPL.getCode() to 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.

Chetan Kinger
  • 15,069
  • 6
  • 45
  • 82
  • It's working!!! Why it's the difference between ? Why the == doesn't work? – Alexandre Picard-Lemieux Jun 23 '15 at 19:06
  • Exactly zero elements. But `CodeExecutionChaine.A.getCode()` should be returned in that case. Why NoSuchElementException? –  Jun 23 '15 at 21:16
  • 1
    @saka1029 None of the methods that you use can directly throw that `Exception`. Please post your stack trace in your question for further analysis. Also confirm that you are showing us the same code that you are facing the issue with. – Chetan Kinger Jun 24 '15 at 07:51