Bradley Bradley - 1 year ago 72
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
returns null:

return ? :

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


The "profiles" is a HashMap:

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

Answer Source

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download