1+ import java .util .Map ;
2+ import java .util .TreeMap ;
3+
4+ public class RemoveEntriesFromTreeMapExample {
5+ public static void main (String [] args ) {
6+ TreeMap <String , String > countryISOCodeMapping = new TreeMap <>();
7+
8+ countryISOCodeMapping .put ("India" , "IN" );
9+ countryISOCodeMapping .put ("United States of America" , "US" );
10+ countryISOCodeMapping .put ("China" , "CN" );
11+ countryISOCodeMapping .put ("United Kingdom" , "UK" );
12+ countryISOCodeMapping .put ("Russia" , "RU" );
13+ countryISOCodeMapping .put ("Japan" , "JP" );
14+
15+ System .out .println ("CountryISOCodeMapping : " + countryISOCodeMapping );
16+
17+ // Remove the mapping for a given key
18+ String countryName = "Japan" ;
19+ String isoCode = countryISOCodeMapping .remove (countryName );
20+ if (isoCode != null ) {
21+ System .out .println ("Removed (" + countryName + " => " + isoCode + ") from the TreeMap. New TreeMap " + countryISOCodeMapping );
22+ } else {
23+ System .out .println (countryName + " does not exist, or it is mapped to a null value" );
24+ }
25+
26+ // Remove the mapping for a given key only if it is mapped to a given value
27+ countryName = "India" ;
28+ boolean isRemoved = countryISOCodeMapping .remove (countryName , "IA" );
29+ System .out .println ("Was the mapping removed for " + countryName + "? : " + isRemoved );
30+
31+ // Remove the first entry from the TreeMap
32+ Map .Entry <String , String > firstEntry = countryISOCodeMapping .pollFirstEntry ();
33+ System .out .println ("Removed firstEntry : " + firstEntry + ", New TreeMap : " + countryISOCodeMapping );
34+
35+ // Remove the last entry from the TreeMap
36+ Map .Entry <String , String > lastEntry = countryISOCodeMapping .pollLastEntry ();
37+ System .out .println ("Removed lastEntry : " + lastEntry + ", New TreeMap : " + countryISOCodeMapping );
38+ }
39+ }
0 commit comments