Search code examples
javaif-statementforeachhashmapreturn

Java boolean "Unexpected return value"


I'm new to Java and I can't understand why the IDE says that "Unexpected return value" inside the forEach where I declared that the boolean is true or false by an If statement. My goal is to check that there is an object inside the "States" HashMap which already uses the name that I want to set to a new state. (The HashMap's key is a String which is called IdentifierOfState and the value is my State object which contains variables like its name.) Thank you for your help in advance!

public boolean isStateNameClaimed(String NameOfState)
{
    States.forEach((IdentifierOfState, ValueOfState) ->
    {
        if (ValueOfState.getNameOfState().equalsIgnoreCase(NameOfState)) {return true;}
        else {return false;}
    });
    return false;
}

Solution

  • The problem is that you are attempting to return the results in the wrong place. The {return true;} and {return true;} are in a lambda, so they are attempting to return a result for the lambda. But the inferred type signature for that lambda doesn't allow any values to be returned.

    If your intention is that those return statements should be returning a result from isStateNameClaimed, then the better solution is to just use a for loop to iterate the elements of States.


    It doesn't help things that your Java code contains a number of egregious Java style violations. You should NOT start the name of a variable with an upper-case letter. It will confuse ... and then annoy ... other people reading your code.

    You may say: "Nah, I don't need to follow the rules, 'cos nobody else will be reading my code". But you are asking >>us<< to read your code.

    I'm new to Java ...

    ... so NOW is the time to learn to do it correctly. Java style matters to people reading your code.


    This is how I would write it in classic Java:

    public boolean isStateNameClaimed(String name) {
        for (State v: states.values()) {
            if (v.getNameOfState().equalsIgnoreCase(name)) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }
    

    Or using streams:

    public boolean isStateNameClaimed(String name) {
        return states.values().stream().anyMatch(
            (v) -> v.getNameOfState().equalsIgnoreCase(name));
    }
    

    Actually ... I just noticed that those two solutions are not equivalent. And based on your description of what you are trying to do, it probably means that the first one and your original attempt are algorithmically incorrect.