Bradley Bradley - 27 days ago 10
Java Question

Making this HashMap != null shorter?

So I have this code,

public Profile getProfile(Player player)
{
if (profiles.get(player) != null)
{
return profiles.get(player);
}

return new Profile(player);
}


I was wondering if there is a way to shorten the != null part, but not returning null, I've seen this sort of syntax used, cutting it down to one line by creating the player's profile if the
get()
returns null:

return ? :

Sorry, I can't remember what it is called would appreciate the help.

Edit:

The "profiles" is a HashMap:

private HashMap<Player, Profile> profiles = new HashMap<>();

Answer

If you want to ensure that the map is not changed by this call, you can use the Optional class:

public Profile getProfile(Player player)
{
    return Optional.ofNullable(profiles.get(player)).orElseGet(() -> new Profile(player));
}
Comments