Java Program to get Tail Map from TreeMap

Java 8Object Oriented ProgrammingProgramming

<p>To get Tail Map from TreeMap, let us first create a TreeMap and set key-value pair &minus;</p><pre class="result notranslate">TreeMap&lt;String, String&gt;tMap = new TreeMap&lt;String, String&gt;(); tMap.put(&quot;1&quot;, &quot;A&quot;); tMap.put(&quot;2&quot;, &quot;B&quot;); tMap.put(&quot;3&quot;, &quot;C&quot;); tMap.put(&quot;4&quot;, &quot;D&quot;); tMap.put(&quot;5&quot;, &quot;E&quot;); tMap.put(&quot;6&quot;, &quot;F&quot;); tMap.put(&quot;7&quot;, &quot;G&quot;);</pre><p>Now, let&rsquo;s say you need to get the tailmap from 2 i.e. all the key-value pairs after 2. For that, use the method tailMap() &minus;</p><pre class="result notranslate">SortedMapmap = tMap.tailMap(&quot;2&quot;);</pre><h2>Example</h2><p><a class="demo" href="http://tpcg.io/rNAbDv" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">import java.util.SortedMap; import java.util.TreeMap; public class Demo { &nbsp; &nbsp;public static void main(String[] args) { &nbsp; &nbsp; &nbsp; TreeMap&lt;String, String&gt;tMap = new TreeMap(); &nbsp; &nbsp; &nbsp; tMap.put(&quot;1&quot;, &quot;A&quot;); &nbsp; &nbsp; &nbsp; tMap.put(&quot;2&quot;, &quot;B&quot;); &nbsp; &nbsp; &nbsp; tMap.put(&quot;3&quot;, &quot;C&quot;); &nbsp; &nbsp; &nbsp; tMap.put(&quot;4&quot;, &quot;D&quot;); &nbsp; &nbsp; &nbsp; tMap.put(&quot;5&quot;, &quot;E&quot;); &nbsp; &nbsp; &nbsp; tMap.put(&quot;6&quot;, &quot;F&quot;); &nbsp; &nbsp; &nbsp; tMap.put(&quot;7&quot;, &quot;G&quot;); &nbsp; &nbsp; &nbsp; tMap.put(&quot;8&quot;, &quot;H&quot;); &nbsp; &nbsp; &nbsp; tMap.put(&quot;9&quot;, &quot;I&quot;); &nbsp; &nbsp; &nbsp; tMap.put(&quot;10&quot;, &quot;J&quot;); &nbsp; &nbsp; &nbsp; SortedMap map = tMap.tailMap(&quot;2&quot;); &nbsp; &nbsp; &nbsp; System.out.println(&quot;Sub Map = &quot; + map); &nbsp; &nbsp; &nbsp; map = tMap.tailMap(&quot;8&quot;); &nbsp; &nbsp; &nbsp; System.out.println(&quot;Sub Map = &quot; + map); &nbsp; &nbsp; &nbsp; map = tMap.tailMap(&quot;1&quot;); &nbsp; &nbsp; &nbsp; System.out.println(&quot;Sub Map = &quot; + map); &nbsp; &nbsp;} }</pre><h2>Output</h2><pre class="result notranslate">Sub Map = {2=B, 3=C, 4=D, 5=E, 6=F, 7=G, 8=H, 9=I} Sub Map = {8=H, 9=I} Sub Map = {1=A, 10=J, 2=B, 3=C, 4=D, 5=E, 6=F, 7=G, 8=H, 9=I}</pre>
raja
Updated on 30-Jul-2019 22:30:25

Advertisements