Java Program to get headset from TreeSet

Java 8Object Oriented ProgrammingProgramming

<p>To get HeadSet from TreeSet, at first create a TreeSet and add some elements:</p><pre class="result notranslate">TreeSet&lt;String&gt; treeSet = new TreeSet&lt;String&gt;(); treeSet.add(&quot;ABC&quot;); treeSet.add(&quot;DEF&quot;); treeSet.add(&quot;GHI&quot;); treeSet.add(&quot;JKL&quot;); treeSet.add(&quot;MNO&quot;); treeSet.add(&quot;PQR&quot;);</pre><p>To get headset, use the headset() method:</p><pre class="result notranslate">SortedSet&lt;String&gt; set = treeSet.headSet(&quot;MNO&quot;); System.out.println(&quot;Head Set = &quot; + set);</pre><p>You can also change the value like this:</p><pre class="result notranslate">set = treeSet.headSet(&quot;GHI&quot;); System.out.println(&quot;Head Set = &quot; + set);</pre><h2>Example</h2><pre class="prettyprint notranslate">import java.util.SortedSet; import java.util.TreeSet; public class Demo { &nbsp; &nbsp;public static void main(String[] args) { &nbsp; &nbsp; &nbsp; TreeSet&lt;String&gt; treeSet = new TreeSet&lt;String&gt;(); &nbsp; &nbsp; &nbsp; treeSet.add(&quot;ABC&quot;); &nbsp; &nbsp; &nbsp; treeSet.add(&quot;DEF&quot;); &nbsp; &nbsp; &nbsp; treeSet.add(&quot;GHI&quot;); &nbsp; &nbsp; &nbsp; treeSet.add(&quot;JKL&quot;); &nbsp; &nbsp; &nbsp; treeSet.add(&quot;MNO&quot;); &nbsp; &nbsp; &nbsp; treeSet.add(&quot;PQR&quot;); &nbsp; &nbsp; &nbsp; SortedSet&lt;String&gt; set = treeSet.headSet(&quot;MNO&quot;); &nbsp; &nbsp; &nbsp; System.out.println(&quot;Head Set = &quot; + set); &nbsp; &nbsp; &nbsp; set = treeSet.headSet(&quot;GHI&quot;); &nbsp; &nbsp; &nbsp; System.out.println(&quot;Head Set = &quot; + set); &nbsp; &nbsp; &nbsp; set = treeSet.headSet(&quot;ABC&quot;); &nbsp; &nbsp; &nbsp; System.out.println(&quot;Head Set = &quot; + set); &nbsp; &nbsp;} }</pre><h2>Output</h2><pre class="result notranslate">Head Set = [ABC, DEF, GHI, JKL] Head Set = [ABC, DEF] Head Set = []</pre>
raja
Updated on 30-Jul-2019 22:30:25

Advertisements