views:

34

answers:

3

I am able to compare Strings fine, but would like to know how I can rank floating point numbers?

getChange() returns a String. I want to be able to sort descending. How can I do this?

UPDATE:

package org.stocktwits.helper;

import java.util.Comparator;

import org.stocktwits.model.Quote;

public class ChangeComparator implements Comparator<Quote>
{
    public int compare(Quote o1, Quote o2) {
        float change1 = Float.valueOf(o1.getChange());
        float change2 = Float.valueOf(o2.getChange());

        if (change1 < change2) return -1;
        if (change1 == change2) return 0; // Fails on NaN however, not sure what you want
        if (change2 > change2) return 1;
    }
}

I am getting the compile time error:

This method must return a result of type int    ChangeComparator.java   
A: 

You can compare floats with the basic arithmetic operators, e.g. < or >.

public class ChangeComparator implements Comparator<Quote>
{
    public int compare(Quote o1, Quote o2) {
        return o1.getChange() < o2.getChange();
    }
}
William
This won't compile :)
BalusC
+1  A: 

Read the javadoc of Comparator#compare() method.

Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

So, basically:

float change1 = o1.getChange();
float change2 = o2.getChange();
if (change1 < change2) return -1;
if (change2 > change2) return 1;
return 0;

Or if you like conditional operators:

return o1.getChange() < o2.getChange() ? -1 
     : o2.getChange() > o2.getChange() ? 1 
     : 0;

You however need to take account with Float.NaN, I am not sure how you'd like to have them ordered. First? Last? Equally?

BalusC
watch out for Float.NaN! I'm presuming your data doesn't have NaNs, but since NaN on one side of any comparison will always return false (even Float.NaN==Float.NaN is false!), you might want a Float.isNaN(change1) or whatever check. otherwise the sort will be apparently random if there are NaN's involved.
John Gardner
I am getting the compile time error (see updated code in my question): This method must return a result of type int ChangeComparator.java
Sheehan Alam
The compilation error speaks for itself. You need to make sure that it **always** returns an `int`. I'll edit the example.
BalusC
+1  A: 

How about this:

public class ChangeComparator implements Comparator<Quote>
{
    public int compare(Quote o1, Quote o2) {
        Float change1 = Float.valueOf(o1.getChange());
        Float change2 = Float.valueOf(o2.getChange());
        return change1.compareTo(change2);
    }
}
spong
This is the best answer - delegate the comparison to Float's compareTo.
Steve Kuo