Search a key in TreeMap?

This example shows how to find out whether a specific key exists in the TreeMap or not. By using containsKey() method you can find out keys presence in the TreeMap.


								
package MindcluesTreeMap;

import java.util.TreeMap;

/**
 *
 * @author Mindclues
 */
public class KeySearching {

    public static void main(String a[]) {
        TreeMap tmap = new TreeMap();

        //add key-value pair to TreeMap
        tmap.put("one", "mindclues1");
        tmap.put("two", "mindclues2");
        tmap.put("three", "mindclues3");
        tmap.put("four", "mindclues4");
        tmap.put("five", "mindclues5");
        System.out.println(tmap);
        if (tmap.containsKey("one")) {
            System.out.println("The TreeMap contains key first");
        } else {
            System.out.println("The TreeMap does not contains key first");
        }
        if (tmap.containsKey("six")) {
            System.out.println("The TreeMap contains key six");
        } else {
            System.out.println("The TreeMap does not contains key six");
        }
    }
}

							

								
{five=mindclues5, four=mindclues4, one=mindclues1, three=mindclues3, two=mindclues2}
The TreeMap contains key first
The TreeMap does not contains key six
							

Related Articles

post a comment