TreeMap
Check value existence in TreeMap example
This is an example of how to check a value existence in a TreeMap in Java. Checking if a value exists in a TreeMap implies that you should:
- Create a new TreeMap.
- Populate the map with elements, with
put(K key, V value)
API method of TreeMap. - Invoke
containsValue(Object value)
API method of TreeMap. The method returns true if this map maps one or more keys to the specified value and false otherwise.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.util.TreeMap; public class CheckValueTreeMap { public static void main(String[] args) { // Create a TreeMap and populate it with elements TreeMap treeMap = new TreeMap(); treeMap.put("key_1","element_1"); treeMap.put("key_2","element_2"); treeMap.put("key_3","element_3"); // boolean containsValue(Object key) returns true if the value is mapped to one or more keys otherwise false. boolean exists = treeMap.containsValue("element_2"); System.out.println("element_2 exists in TreeMap ? : " + exists); } }
Output:
element_2 exists in TreeMap ? : true
This was an example of how to check a value existence in a TreeMap in Java.