The java.util.concurrent.ConcurrentMap interface is a thread-safe map containing key-value pairs that allows multiple threads to access and modify the map concurrently without causing any data inconsistency issues. The interface provides several methods for retrieving, inserting, and updating key-value pairs in a thread-safe manner.
Code Examples:
1. Using containsKey() method:
ConcurrentMap concurrentMap = new ConcurrentHashMap<>(); concurrentMap.put(1, "Java"); concurrentMap.put(2, "Python"); concurrentMap.put(3, "Ruby"); if (concurrentMap.containsKey(2)) { System.out.println("Key 2 is present in the map with value " + concurrentMap.get(2)); } else { System.out.println("Key 2 is not present in the map."); }
In the above code, we have created a ConcurrentMap object named concurrentMap and added some key-value pairs in it. Then we have used the containsKey() method to check if the specified key 2 is present in the map or not.
2. Using the containsKey() method with a custom class:
class Person { private int id; private String name; public Person(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public String getName() { return name; } @Override public boolean equals(Object obj) { if (obj instanceof Person) { return this.id == ((Person) obj).id; } return false; } } ConcurrentMap personMap = new ConcurrentHashMap<>(); personMap.put(new Person(1, "John"), "USA"); personMap.put(new Person(2, "Jack"), "UK"); personMap.put(new Person(3, "Albert"), "France"); Person person = new Person(2, "Jack"); if (personMap.containsKey(person)) { System.out.println("Person with ID " + person.getId() + " is present in the map with value " + personMap.get(person)); } else { System.out.println("Person with ID " + person.getId() + " is not present in the map."); }
In the above code, we have created a custom class named Person and used it as the key in the ConcurrentMap. We have overridden the equals() method to check equality based on the person's ID. Then we have added some Person objects in the map and used the containsKey() method to check if the specified Person object is present in the map or not.
The java.util.concurrent package library contains the ConcurrentMap interface.
Java ConcurrentMap.containsKey - 30 examples found. These are the top rated real world Java examples of java.util.concurrent.ConcurrentMap.containsKey extracted from open source projects. You can rate examples to help us improve the quality of examples.