Insert a non-existent value into a Map in Java 8
February 21, 2015 Leave a comment
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) { this.id = id; this.name = name; this.age = age; } public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.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.