How to Find a Key in a TreeMap in Java
To check if a key exists in TreeMap in Java, you need to call the method containsKey() of the TreeMap.
public boolean containsKey(): This method returns a true Boolean if the key you are looking for is in the TreeMap.
listTo get the value of the key you are looking for in TreeMap in Java, you need to call the get(key).
public Object get(Object key): this method returns the value of the key you are looking for if it exists.
JavaDoc: containsKey() method
public boolean containsKey(): This method returns a true Boolean if the key you are looking for is in the TreeMap.
listTo get the value of the key you are looking for in TreeMap in Java, you need to call the get(key).
public Object get(Object key): this method returns the value of the key you are looking for if it exists.
import java.util.*;The execution of this code gives:
public class recherche_treemap {
public static void main(String[] args) {
// creating TreeMap
TreeMap< String, String> treemap_langue = new TreeMap< String, String> ();
// insertion in treemap
treemap_langue.put("fr", "français");
treemap_langue.put("en", "English");
treemap_langue.put("es", "Spanish");
treemap_langue.put("it", "Italian");
treemap_langue.put("ge", "German");
//browse keys with Iterator
System.out.println("Code List");
Set set=treemap_langue.keySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()){
String key = ((String) iterator.next());
System.out.println(key);
}
boolean exists = treemap_langue.containsKey("es");
System.out.println("the es key exists in the list: "+exists);
String value = treemap_langue.get("en");
System.out.println("en is the code for: "+value);
}
}
Code ListReferences:
en
es
fr
ge
it
the es key exists in the list: true
en is the code for: english
JavaDoc: containsKey() method