'TreeSet Sorting Order Confusion

I know that TreeSet in Java sort its elements in ascending order. For integer it would be 1, 2, 3, 4, 5, for String it would be alphabetical. However, what if I want to input objects in that TreeSet, how it is going to be sorted by default?



Solution 1:[1]

That object must either implement Comparable

class MyObject implements Comparable<MyObject>
{
  int value;

  MyObject(int value)
  {
    this.value=value;
  }

  //Sorting order controlled here
  @Override
  public int compareTo(MyObject m)
  {
    return Integer.compare(this.value,m.value);
  }
}

TreeSet<MyObject> set=new TreeSet();
//add stuff here

Or you supply your own Comparator. Use lambda expressions with java 7 and above

TreeSet<MyObject> set=new TreeSet((obj1,obj2)->Integer.compare(obj1.value,obj2.value));

Comparator takes precedence over Comparable and your object dosen't need to implement Comparable which is useful for 3rd party libraries which don't implement the interface

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sync it