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

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 :

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

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