Home > database >  Java - Comparing 2 floats (or doubles)
Java - Comparing 2 floats (or doubles)

Time:12-27

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.

CodePudding user response:

Simply:

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

Float#compareTo(java.lang.Float)

CodePudding user response:

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

  • Related