Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.NoSuchElementException: No value present Java 8 Lambda [duplicate]

Tags:

java

lambda

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

like image 715
Alexandre Picard-Lemieux Avatar asked Jun 09 '26 20:06

Alexandre Picard-Lemieux


1 Answers

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.

like image 113
Chetan Kinger Avatar answered Jun 11 '26 10:06

Chetan Kinger