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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s


A great site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: