Comparator like a lambda

I have the following method in a Java library :

public void setColumnComparator(final int columnIndex, final Comparator<T> columnComparator)

The idea says that she has the following prototype:

setColumnComparator(columnIndex: Int, columnComparator: ((Any!, Any!) -> Int)!)

How can i use it? I know that it will be String, so I want something like this, but it does not compile.

setColumnComparator(0, Comparator<String> { a, b -> a.compareTo(b) }
+4
source share
2 answers

If you look more closely, you need to pass a comparator that compares the full values, not the values ​​in the column. So, let's say that the data type is in your table Car(so you have one SortableTableView<Car>), and the first column contains the model names. Then you will write

setColumnComparator(0, { a, b -> a.modelName.compareTo(b.modelName) }

Or better:

setColumnComparator(0, compareBy({ it.modelName })

(see https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/compare-by.html )

IDEA SortableTableView<Any> SortableTableView<*>. . , Car Book:

compareBy({ (it as? Car)?.modelName }, { (it as? Book)?.title })
+2

, SortableTableView String, SortableTableView<String> :

(tableView as SortableTableView<String>).setColumnComparator(1, { x, y ->
    x.compareTo(y)
})

, Comparator :

tableView.setColumnComparator(1, { x, y -> 
    (x as String).compareTo(y as String) 
})
+1

Source: https://habr.com/ru/post/1689302/


All Articles