<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by preeti theraja on Medium]]></title>
        <description><![CDATA[Stories by preeti theraja on Medium]]></description>
        <link>https://medium.com/@preeti.theraja18?source=rss-a9fb9e335963------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*HN7GCsKj_H9MmPcpsy0kag.jpeg</url>
            <title>Stories by preeti theraja on Medium</title>
            <link>https://medium.com/@preeti.theraja18?source=rss-a9fb9e335963------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 05:00:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@preeti.theraja18/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[TreeMap Internals]]></title>
            <link>https://medium.com/xebia-engineering/treemap-internals-199e0e0050b5?source=rss-a9fb9e335963------2</link>
            <guid isPermaLink="false">https://medium.com/p/199e0e0050b5</guid>
            <category><![CDATA[collection]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[treemap]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[preeti theraja]]></dc:creator>
            <pubDate>Thu, 05 Dec 2019 08:31:19 GMT</pubDate>
            <atom:updated>2019-12-05T08:31:19.585Z</atom:updated>
            <content:encoded><![CDATA[<p>Learning anything with more in-depth knowledge makes us more confident. This tutorial will provide the internal implementation details of TreeMap. It will help that how the values are stored inside a hierarchical structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*Xi7BK95nIPyLUliY" /></figure><p>To start with, <em>TreeMap</em> is a map implementation that keeps its entries sorted according to the natural ordering of its keys or better still using a comparator if provided by the user at construction time.</p><pre>Class TreeMap&lt;K,V&gt;</pre><h4>Type Parameters:</h4><h4>K — the type of keys maintained by this map</h4><h4>V — the type of mapped values</h4><p>As the name itself suggests, the working of TreeMap is based on the tree data structure. Each node in the tree will have three references, i.e. its parent, right and left element.</p><ul><li>The left element will always be logically less than the parent element.</li><li>The right element will always be logically greater than OR equal to the parent element.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/0*07vVcXuY5BUTu6uh" /></figure><p>Now let’s see How TreeMap works, TreeMap is nothing like HashMap; except the fact that it is an implementation of Map interface. TreeMap does not use hashing for storing keys. It uses a data structure called the Red-Black tree. This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.</p><p>First of all, a red-black tree is a data structure that consists of nodes; picture an inverted mango tree with its root in the sky and the branches growing downward. The root will contain the first element added to the tree.</p><p>A red-black tree is similar in structure to a <a href="https://en.wikipedia.org/wiki/B-tree">B-tree</a> of order 4, where each node can contain between 1 and 3 values and (accordingly) between 2 and 4 child pointers. In such a B-tree, each node will contain only one value matching the value in a black node of the red-black tree, with an optional value before and/or after it in the same node, both matching an equivalent red node of the red-black tree.</p><p>The rule is that starting from the root, any element in the left branch of any node is always less than the element in the node itself. Those on the right are always greater. What defines greater or less than is determined by the natural ordering of the elements or the defined comparator at construction time.</p><p>This rule guarantees that the entries of a Treemap will always be in sorted and predictable order.</p><p>Secondly, a red-black tree is a self-balancing binary search tree. This attribute and the above guarantee that basic operations like search, get, put and remove take logarithmic time <em>O(log n)</em>.</p><p>Being self-balancing is key here. As we keep inserting and deleting entries, picture the tree growing longer on one edge or shorter on the other.</p><p>This would mean that an operation would take a shorter time on the shorter branch and longer time on the branch which is furthest from the root, something we would not want to happen.</p><p>Therefore, this is taken care of in the design of red-black trees. For every insertion and deletion, the maximum height of the tree on any edge is maintained at <em>O(log n) </em>i.e. the tree balances itself continuously.</p><p>The following requirements must be satisfied by a red-black tree:</p><ol><li>Each node is either red or black.</li><li>The root is black. This rule is sometimes omitted. Since the root can always be changed from red to black, but not necessarily vice versa, this rule has little effect on analysis.</li><li>All leaves (NIL) are black.</li><li>If a node is red, then both its children are black.</li><li>Every <a href="https://en.wikipedia.org/wiki/Path_(graph_theory)">path</a> from a given node to any of its descendant NIL nodes contains the same number of black nodes.</li></ol><h3>Let’s understand step by step.</h3><p><strong>Step 1:</strong> Initially when we create a TreeMap object as</p><pre>Map&lt;Key, String&gt; treemap = new TreeMap&lt;&gt;();</pre><p>There are no elements in it. Let’s add the first element to it.</p><p><strong>Step 2: Adding the first element into TreeMap</strong></p><pre>treemap.put(new Key(“Amita”), “Amita”);</pre><p>So {“Amita”} is the first key object being inserted as key. This element will be the root node for the tree .</p><p><strong>Step 3: Adding the second element into TreeMap</strong></p><pre>treemap.put(new Key(“Radhika”), “Radhika”);</pre><p>Now, {“Radhika”} is logically greater than {“Amrita”} and hence according to our rules,</p><ul><li>{“Radhika”} will be placed to the right of {“Amrita”}.</li><li>{“Amrita”} will be a parent of {“Radhika”}</li></ul><p><strong>Step 4: Adding the third element into TreeMap</strong></p><pre>treemap.put(new Key(“Dinesh”), “Dinesh”);</pre><p>So {“Dinesh”} is the first key object being inserted as key. This element will be the root node for the tree.</p><p>As we have discussed above properties and rules of the Red-Black tree, the Red-Black tree implementation will give us sorted order from left to right. So, elements of a tree become as below.</p><ul><li>{“Amrita”} will be to the left of {“Dinesh”}</li><li>{“Radhika”} will be to the right of {“Dinesh”}</li></ul><p>Some of the important points to remember about TreeMap in java are;</p><ol><li>Apart from implementing the Map interface, Java TreeMap also implements NavigableMap and indirectly implements the SortedMap <a href="https://www.journaldev.com/1601/interface-in-java">interface</a>. TreeMap also extends AbstractMap class.</li><li>TreeMap entries are sorted in the natural ordering of its keys. It also provides a constructor to provide <a href="https://www.journaldev.com/780/comparable-and-comparator-in-java-example">Comparator</a> to be used for ordering. So if you are using any class as key, make sure it’s implementing <a href="https://www.journaldev.com/780/comparable-and-comparator-in-java-example">Comparable interface</a> for natural ordering.</li><li>Java TreeMap implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.</li><li>TreeMap is not synchronized and hence not thread-safe. For multithreaded environments, you can get a wrapped synchronized using Collections.synchronizedSortedMap method.</li><li>TreeMap methods to get keyset and values return <a href="https://www.journaldev.com/13460/java-iterator">Iterator</a> that is fail-fast in nature, so any concurrent modification will throw <a href="https://www.journaldev.com/378/java-util-concurrentmodificationexception">ConcurrentModificationException</a>.</li><li>TreeMap in java doesn’t allow null keys, however, you can have multiple null values associated with different keys.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=199e0e0050b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/xebia-engineering/treemap-internals-199e0e0050b5">TreeMap Internals</a> was originally published in <a href="https://medium.com/xebia-engineering">Xebia Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>