Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

incompatible types: unexpected return value in java program

I wanted to return true/false if the id is present in the array List but while returning the OP from the method I’m getting

java: incompatible types: unexpected return value

public boolean getMemberIfPresent(String id, List<Member>  memberRes ){
    try {
      memberRes.stream().iterator().forEachRemaining(c -> {
        if(c.getId().equals(id)){
          return true;
        }
      });
    }catch (Exception e){
      return false;
    }
    return false;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use an enhanced for instead of using the forEach method. You’re returning from the lambda, not from your method.

public boolean getMemberIfPresent(String id, List<Member>  memberRes ){
    try {
      for (var c : memberRes) {
        if(c.getId().equals(id)){
          return true;
        }
      }
    }catch (Exception e){
      return false;
    }
    return false;
}

Or, if you want to do it in a more functional way, do it properly with a stream

public boolean getMemberIfPresent(String id, List<Member>  memberRes ){
    try {
        return memberRes.stream()
                        .map(Member::getId)
                        .anyMatch(id::equals);
    } catch (Exception e) {
        return false;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading