
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If a Particular Value Exists in TreeMap in Java
In this article, we will learn to check if a particular value exists in TreeMap in Java. A Java TreeMap is an ordered map that keeps key-value pairs in ascending order of keys. Although it is efficient to look up a key, checking for a value is inefficient since one has to iterate over the values.
What is TreeMap?
A TreeMap is a Red-Black tree-based implementation it is a part of java.util package and implements the NavigableMap interface. It maintains the natural ordering of keys or a custom order defined by a Comparator. Since it is sorted by keys, searching for values is not as efficient as searching for keys.
Checking if a Value Exists in TreeMap
To check if a particular value exists in TreeMap, use the containsValue() method. This method returns true if the specified value is found; otherwise, it returns false.
boolean containsValue(Object value)
-
Parameters: The value to be checked for existence.
- Returns: true if the value exists, false otherwise.
Create a TreeMap first and add some elements using the put() method ?
TreeMap<Integer,String> m = new TreeMap<Integer,String>(); m.put(1,"PHP"); m.put(2,"jQuery"); m.put(3,"JavaScript"); m.put(4,"Ruby"); m.put(5,"Java"); m.put(6,"AngularJS"); m.put(7,"ExpressJS");
Now, let's say we need to check whether the value "Java" exists or not. For that, use the containsValue() method like this ?
m.containsValue("Java")
Example
The following is an example to check if a particular value exists in TreeMap ?
import java.util.*; public class Demo { public static void main(String args[]) { TreeMap<Integer,String> m = new TreeMap<Integer,String>(); m.put(1,"PHP"); m.put(2,"jQuery"); m.put(3,"JavaScript"); m.put(4,"Ruby"); m.put(5,"Java"); m.put(6,"AngularJS"); m.put(7,"ExpressJS"); System.out.println("TreeMap Elements...\n"+m); System.out.println("Does value PHP exist in the TreeMap = "+m.containsValue("Java")); } }
Output
TreeMap Elements... {1=PHP, 2=jQuery, 3=JavaScript, 4=Ruby, 5=Java, 6=AngularJS, 7=ExpressJS} Does value PHP exist in the TreeMap = true
Time complexity: O(n), as it iterates through all values.
Space complexity: O(1), since it does not use extra space.
Conclusion
The containsValue() method is a simple and effective way to check if a specific value exists in a TreeMap. However, since it requires scanning all values, its time complexity is O(n), making it less efficient than key lookups. If frequent value searches are needed, consider using a bi-directional map or maintaining an additional HashSet of values for faster lookups.