Search code examples
javaarraylistcomparatorcomparable

Comparator for sorting an object arraylist by float parameter


How can i create a comparator to be able to sort an arraylist by a float parameter?

Imagine i have an arraylist of objects that has something like this:

ID=7 TFIDF=0.12654299 PR=25238.0
ID=4 TFIDF=0.12654299 PR=3638.0
ID=4 TFIDF=0.12654299 PR=3638.0
ID=4 TFIDF=0.12654299 PR=3638.0
ID=3 TFIDF=0.56442446 PR=14558.0
ID=1 TFIDF=0.0083091585 PR=3953.0 

I want to sort the array by TFIDF values.. As far as i know i can only sort them by integer.. Thus, im comparing zeros.

So far i have this:

Collections.sort(Contents_To_Show, new Comparator<ContentToShow>() {
            public int compare(ContentToShow o1, ContentToShow o2) {
                return (int) (o1.GetPR() - o2.GetPR());
            }
        });

But. Again, it compares me only the integer part. How can i compare the entire value?

Please help.

Thanks


Solution

  • Followup to Pedro's followup. If you want to sort by TFIDF, then by PR,

    int result = Float.compare(o1.getTFIDF(), o2.getTFIDF());
    if (result == 0)
      result = Float.compare(o1.getPR(), o2.getPR());
    return result;