title: How to retrieve elements from sorted TreeSet using Binary Search?
body: <p>I am trying to merge multiple sorted lists into one TreeSet.. And then I am thinking to apply Binary Search algorithm on that TreeSet to retrieve the element in O(log n) time complexity..</p>
  
  <p>Below is my code in which I am passing List of Lists in in one of my method and combining them into <code>TreeSet</code> to avoid duplicacy... All the lists inside <code>inputs</code> are sorted -</p>
  
  <pre><code>private TreeSet&lt;Integer&gt; tree = new TreeSet&lt;Integer&gt;();
  
  public void mergeMultipleLists(final List&lt;List&lt;Integer&gt;&gt; inputs) {
      tree = new TreeSet&lt;Integer&gt;();
      for (List&lt;Integer&gt; input : inputs) {
          for(Integer ii : input) {
              tree.add(ii);
          }
      }
  }
  
  public List&lt;Integer&gt; getItem(final Integer x) {
      // extract elements from TreeSet in O(log n)
  }
  </code></pre>
  
  <ul>
  <li>First of all, is this right way to merge multiple sorted lists into TreeSet? Is there any direct way to merge multiple sorted lists in TreeSet efficiently?</li>
  <li>Secondly, how would I extract an element from that TreeSet in O(log n) time complexity? I would like to find an element <code>x</code> in that <code>TreeSet</code>, if it is there, then return it, if it is not there then return the next largest value from the <code>TreeSet</code>.</li>
  </ul>
  
  <p>Or may be I am better off to another data structure as compared to which I am using currently?</p>
  
  <p><strong>UPDATED CODE:-</strong></p>
  
  <p>private TreeSet tree = new TreeSet();</p>
  
  <pre><code>public SearchItem(final List&lt;List&lt;Integer&gt;&gt; inputs) {
      tree = new TreeSet&lt;Integer&gt;();
      for (List&lt;Integer&gt; input : inputs) {
          tree.addAll(input);
      }
  }
  
  public Integer getItem(final Integer x) {
      if(tree.contains(x)) {
          return x;
      } else {
          // now how do I extract next largest 
           // element from it if x is not present
      }
  }
  </code></pre>