TreeSet constructor with Comparator<?> parameter

All the above answers are correct, but I would like to add that a custom Comparator, apart from resulting in a different sorting, will also filter values differently.

Since Set's values are univocal, if the custom Comparator returns that two values are identical only one of them will appear in the Set:

    Set<String> s = new TreeSet<>(new Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            return s1.trim().compareTo(s2.trim());
        }
    });

    s.add("1");
    s.add(" 1");
    s.add("2 ");
    s.add("2");
    s.add(" 2 ");   

    Arrays.toString(s.toArray()); // [ "1", "2 "]

The elements in a TreeSet are kept sorted.

If you use a constructor that has no Comparator, the natural ordering of the element class (defined by the implementation of Comparable) would be used to sort the elements of the TreeSet.

If you want a different ordering, you supply a Comparator in the constructor.