Insert a non-existent value into a Map in Java 8

Consider the following Employee class:

public class Employee
    private UUID id;
    private String name;
    private int age;

    public Employee(UUID id, String name, int age)
    { = id; = name;
        this.age = age;
    public UUID getId()
        return id;

    public void setId(UUID id)
    { = id;

    public String getName()
        return name;

    public void setName(String name)
    { = name;
    public int getAge()
        return age;

    public void setAge(int age)
        this.age = age;

Let’s put some Employee objects into a hash map:

Map<Integer, Employee> employeeMap = new HashMap<>();
employeeMap.put(1, new Employee(UUID.randomUUID(), "Elvis", 50));
employeeMap.put(2, new Employee(UUID.randomUUID(), "Marylin", 18));
employeeMap.put(3, new Employee(UUID.randomUUID(), "Freddie", 25));

Suppose that we run the below bit of code later on in the programme:

employeeMap.put(2, new Employee(UUID.randomUUID(), "Anna", 20));

You’ll probably know that this will replace the original record at key 2 – Marylin – with the new one – Anna.

This can be prevented in Java 8 with the new putIfAbsent method:

employeeMap.putIfAbsent(2, new Employee(UUID.randomUUID(), "Anna", 20));

This bit of code won’t have any effect on the employee map as key 2 already exists.

View all posts related to Java here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: