ConcurrentHashMapmap = new ConcurrentHashMap<>(); map.put("apple", 1); map.put("banana", 2); if (map.containsKey("apple")) { System.out.println("Map contains key 'apple'"); } else { System.out.println("Map does not contain key 'apple'"); }
class MyRunnable implements Runnable { private ConcurrentHashMapmap; private String key; public MyRunnable(ConcurrentHashMap map, String key) { this.map = map; this.key = key; } public void run() { if (map.containsKey(key)) { System.out.println("Thread " + Thread.currentThread().getId() + " found key '" + key + "'"); } else { System.out.println("Thread " + Thread.currentThread().getId() + " did not find key '" + key + "'"); } } } ConcurrentHashMap map = new ConcurrentHashMap<>(); map.put("apple", 1); map.put("banana", 2); ExecutorService executor = Executors.newFixedThreadPool(2); executor.submit(new MyRunnable(map, "apple")); executor.submit(new MyRunnable(map, "orange")); executor.shutdown();
Thread 11 found key 'apple' Thread 12 did not find key 'orange'Note how both threads can safely access the map concurrently without interfering with each other. Overall, ConcurrentHashMap is a powerful data structure for multi-threaded programming in Java, and containsKey() is a useful method for checking if a key exists in the map.