beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Remove Key-value mapping from TreeMap example

By Chaitanya Singh | Filed Under: Java Collections

In this tutorial we are gonna see how to remove a Key-value mapping from TreeMap. We are using remove(Object key) method of TreeMap class to perform this remove.

import java.util.TreeMap;
 
public class Details {
 
  public static void main(String[] args) {
 
    // Create a TreeMap
    TreeMap<String, String> treemap = new TreeMap<String, String>();
 
    // Add key-value pairs to the TreeMap
    treemap.put("Key1","Item1");
    treemap.put("Key2","Item2");
    treemap.put("Key3","Item3");
    treemap.put("Key4","Item4");
    treemap.put("Key5","Item5");
 
    // TreeMap Elements Before remove
    System.out.println("Before: TreeMap contains: "+treemap);

    // Removing element which is mapped to Key3
    /* public V remove(Object key): Removes the mapping 
     * for this key from this TreeMap if present.
     */
    Object removedElement = treemap.remove("Key3");
    System.out.println("Removed Element: "+removedElement);
 
    // TreeMap Elements after remove
    System.out.println("After: TreeMap contains: "+treemap);
  }
}

Output:

Before: TreeMap contains: {Key1=Item1, Key2=Item2, Key3=Item3, Key4=Item4, Key5=Item5}
Removed Element: Item3
After: TreeMap contains: {Key1=Item1, Key2=Item2, Key4=Item4, Key5=Item5}

Reference:
TreeMap – remove(Object key) method

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap