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;
}
>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;
}
}