In Java, containsValue(value) returns true if at least one key in the TreeMap is mapped to value. Values are compared with equals (and null matches a stored null).
A TreeMap is sorted by key, not by value, so it cannot search values quickly: the method walks the entries in key order until it finds a match, which costs O(n) in the worst case.
An instance method of java.util.TreeMap, part of TreeMap since Java 1.2. A TreeMap keeps its key/value pairs sorted by key in a red-black tree, so lookups and updates take O(log n) time; it is not thread-safe.
Seats are keys and passenger names are values, so finding a passenger means searching the values.
Java
import java.util.TreeMap;
public class TreeMapContainsValueSeats {
public static void main(String[] args) {
TreeMap<String, String> seatOf = new TreeMap<>();
seatOf.put("12A", "Ravi");
seatOf.put("12B", "Mona");
seatOf.put("14C", "Ravi");
System.out.println("Ravi has a seat: " + seatOf.containsValue("Ravi"));
System.out.println("Zoe has a seat: " + seatOf.containsValue("Zoe"));
System.out.println("Mona's seat is a key? " + seatOf.containsKey("Mona"));
}
}
Output
Ravi has a seat: true
Zoe has a seat: false
Mona's seat is a key? false
How It Works
Stops at the first match. The scan starts at 12A, whose value is Ravi, so it returns true without looking at the rest.
A full scan for a miss. Zoe is not a value, so every entry is checked before false comes back.
Values are not keys.containsKey("Mona") is false: Mona is stored as a value, and key methods only look at seat numbers.
Example 2 — Integer, Long, and null Values
The value type has to match exactly, and null can be searched too.