Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

comparingDouble and thenComparing  RSS feed

 
Timothy Sam
Ranch Hand
Posts: 751
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm trying to sort a List in reverse order. I can do the code below without a problem:



and that works, but when I try to chain with:



It doesn't work and compiler says it could not resolve the method getAmount? What am I missing here?

Thanks in advance!

Here's my full source

 
Paweł Baczyński
Bartender
Posts: 2054
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, if you need to sort in reverse order, don't use thenComparing(). Use reversed() directly on your original comparator.
Second, if the compiler can not determine the type of s in the lambda you can specify it.

So you'll have
.sorted(Comparator.comparingDouble((Transaction s) -> s.getAmount()).reversed())

It would be even nicer to use a method reference:
.sorted(Comparator.comparingDouble(Transaction::getAmount).reversed())
 
Timothy Sam
Ranch Hand
Posts: 751
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paweł Baczyński wrote:First, if you need to sort in reverse order, don't use thenComparing(). Use reversed() directly on your original comparator.
Second, if the compiler can not determine the type of s in the lambda you can specify it.

So you'll have
.sorted(Comparator.comparingDouble((Transaction s) -> s.getAmount()).reversed())

It would be even nicer to use a method reference:
.sorted(Comparator.comparingDouble(Transaction::getAmount).reversed())


Hi Paweł,

Perfect! Thank you!
 
Pierrot Mongonnam
Greenhorn
Posts: 14
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Timothy,

since somebody gave already the solution of your problem, just one additional Points for you:

the theComparing()-Method and her brothers thenComparingXXX() are to use in case you want to define an additional Comparison criteria if the elements in your stream are equal according - I will call it- to "main comparison" criteria. In other words, in your example your "main comparison" criteria seems to be the amount of a transaction. This is what you expressed in your code: . But if you have 2 differents Transactions with the same amount you could decide to compare according a transaction-ID (if you had it in your code ). Thus you could have something like this: This means "sort the transaction by amount. If equal then sort by transaction-ID".

To summarize:

your way tho use the theCompare() method could'nt work. the argument to pass is not a "reverce Comparator" but what I will call a "key Comparator" instead;
e.g. another key attribute for the comparison (s. thenComparing-API)

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!