Menu
Topics Index
...
`

TreeMapUsingmethods - Java Example Program


TreeMapUsingmethods
import java.util.*;

class TreeMapUsingmethods
{
    TreeMap statecapitals = new TreeMap<>();
    statecapitals.put("Andhra Pradesh", "Hyderabad");
    statecapitals.put("Arunachal Pradesh", "Itanagar");
    statecapitals.put("Bihar", "Patna");
    statecapitals.put("Goa", "Panaji");
    statecapitals.put("Kerala", "Thiruvananthapuram");
    System.out.println(statecapitals); // LINE A
    //Returns true if map contains the key otherwise false
    System.out.println("Map contains key Karnataka : " + statecapitals.containsKey("Karntatka")); // LINE B
    //Returns true if map contains the value otherwise false
    System.out.println("Map contains value Panaji : " + statecapitals.containsValue("Panaji")); // LINE C
    statecapitals.remove("Kerala"); // LINE D
    System.out.println("Map after removing Kerala : "); // LINE E
    System.out.println(statecapitals);// LINE F
}
OUTPUT

{Andhra Pradesh=Hyderabad, Arunachal Pradesh=Itanagar, Bihar=Patna, Goa=Panaji, Kerala=Thiruvananthapuram}
Map contains key Karnataka : false
Map contains value Panaji : true
Map after removing Kerala :
{Andhra Pradesh=Hyderabad, Arunachal Pradesh=Itanagar, Bihar=Patna, Goa=Panaji}

DESCRIPTION

At LINE A the entries in the TreeMap are printed.
At LINE B containsKey is used to know whether map contains key Karnataka
, the return type of the containsKey containValue and method is boolean.
At LINE C containsValue is used to know whether map contains value Panaji. At LINE D the entry Kerala is removed from the map by using remove method.
AT LINE F the map after removing Kerala is printed.

THINGS TO TRY
  • Use entrySet to return a setview of the map as shown below.
    Set<Entry<Integer, String>> setview = statecapitals.entrySet();
    System.out.println("Set view of the entries : " + setview);
    Place the code after LINE F and see the output. Set view of the map is returned.

© meritcampus 2019

All Rights Reserved.

Open In App