0

I'm working with a TableView, in which the column is String type.

I know that the TableView has implemnted itself a sort method for the column.

The problem is that normally I receive a string like a name, but also

  • string starting with a number "5Rose"
  • string "-"

then, by the natural order of sorting, I have as first "-", then a number "5Rose" and a name "Rose".

Instead I need to order as first name "Rose", then number "5Rose" and "-".

I tried to implement a comparator to set in the column,

Comparator naturalOrder = new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {

            //default comparator
            if (o1 == null && o2 == null) {
                return 0;
            }
            if (o1 == null) {                   
                return -1;
            }
            if (o2 == null) {                   
                return 1;
            }

            if (o1 instanceof Comparable) {
                return ((Comparable) o1).compareTo(o2);
            }

            //compare by the characther -
            if (o1 == "-") {
                System.out.println("Triggered");
                return -1;
            }

            return Collator.getInstance().compare(o1.toString(), o2.toString());
        }
    };

    nameColumn.setComparator(Comparator.naturalOrder().thenComparing(naturalOrder));

but I fail.

What I am doing wrong?

  • 1
    `String`s are already `Comparable`, so your `if(o1 instanceof Comparable)` is always true, and you just return the standard comparison from a `String`. Additionally, you use `Comparator.naturalOrder().thenComparing(naturalOrder))`, which will compare the strings by their *natural order* (i.e. using `String.compareTo()`) and only use your comparator if the `String`s are equal. – James_D Apr 22 '20 at 13:54
  • 4
    This just looks like completely the wrong solution anyway; it seems like you're trying to represent multiple data fields (the number, and name, and/or whatever `"-"` represents) in a `String`. Why not create a class encapsulating the data, parse the strings when you read them from wherever you get them, and then make your class `Comparable` with a proper `compareTo` method? – James_D Apr 22 '20 at 13:55
  • 3
    Also don't use `==` to compare Strings: [`equals()` is more reliable](https://stackoverflow.com/a/513839) (e.g. `"-".equals(o1)`) – Emmanuel Chebbi Apr 22 '20 at 14:27

0 Answers0