title: TreeSet Custom Comparator Algo .. String Comparision
body: <p>From the input string provided:</p>
  
  <blockquote>
    <p>{ "200,400,7,1", "100,0,1,1", "200,200,3,1", "0,400,11,1",
    "407,308,5,1","100,600,9,1" } ,</p>
  </blockquote>
  
  <p>I am adding the same in a TreeSet and want it to be sorted with the 3rd element order, so the expected output will be:</p>
  
  <blockquote>
    <p>(100,0,1,1) (200,200,3,1) (407,308,5,1) (200,400,7,1) (100,600,9,1) (0,400,11,1)</p>
  </blockquote>
  
  <p>But my actual output is:</p>
  
  <blockquote>
    <p>(100,0,1,1)(0,400,11,1)(200,200,3,1)(407,308,5,1)(200,400,7,1)(100,600,9,1) </p>
  </blockquote>
  
  <p>But since the string comparison of 11 is less than 9 but in terms of integer , 11>9 . My expected output is getting differed. Suggest me some idea to resolve the same.</p>
  
  <pre><code>import java.util.Comparator;
  import java.util.TreeSet;
  
  public class TreeSetComparator {
  
      public static void main(String[] args) {
          Comparator&lt;String&gt; comparator = new Comparator&lt;String&gt;() {
              @Override
              public int compare(String a, String b) {
                  String aStr = a;
                  String bStr = b;
                  String[] splitA = aStr.split(",");
                  String[] splitB = bStr.split(",");
  
                  return splitA[2].compareTo(splitB[2]);
              }
          };
  
          String[] arr = { "200,400,7,1", "100,0,1,1", "200,200,3,1",
                  "0,400,11,1", "407,308,5,1", "100,600,9,1" };
  
          TreeSet&lt;String&gt; ts = new TreeSet&lt;String&gt;(comparator);
          for (String str : arr) {
              ts.add(str);
          }
  
          for (String element : ts)
              System.out.print(element + " ");
  
      }
  }
  </code></pre>