user14095255
user14095255

Reputation:

Java - Comparing 2 floats (or doubles)

I have an ArrayList that I need to sort by width, which is stored as a float (.getWidth() returns a float)

arrayPlaceholder.sort((m1,m2) -> font.getWidth(m2.getDisplayName()) - font.getWidth(m1.getDisplayName()));

I have looked around the docs and at the error i'm getting, and it's clear that the function .compare(), returns only an int.

Is there any way to compare 2 floats (or doubles, as I can convert floats into doubles); in my usage? I've looked at other posts but I don't want to hardcode this process.

Upvotes: 0

Views: 154

Answers (1)

xerx593
xerx593

Reputation: 13261

Simply:

(m1,m2) -> 
  Float.valueOf( // <- need object wrapper here (only)
    font.getWidth(m1.getDisplayName()))
  .compareTo(
    font.getWidth(m2.getDisplayName())
  )

Float#compareTo(java.lang.Float)

Also possible:

(m1,m2) -> 
  Float.compare( //
    font.getWidth(m1.getDisplayName()),
    font.getWidth(m2.getDisplayName())
  )

For descending order: Switch m1 with m2 (xOr in parameters (m2, m1) xOR in (lambda) body).

Upvotes: 1

Related Questions