0

I am sorting my array list int items by using "compareTo(String string);" this method comparing only string but not int values.How I can sort my array list based on integer value.

Here is my code :

 Collections.sort(mAllSpeedsArray, new AllSpeedsComparator());

public class AllSpeedsComparator implements Comparator<AllSpeeds> {

@Override
public int compare(AllSpeeds lhs, AllSpeeds rhs) {
    // TODO Auto-generated method stub      
        return lhs.getSpeed().compareTo(rhs.getSpeed());        
    }
}
5
  • Sorry, it is early. Not Collections.swap(), Collections.sort(allSpeedsArray); Commented May 2, 2014 at 11:28
  • 1
    Maybe an other possibility is to convert string to integers and then comparing them (> etc ...). To convert: int stringVal = Integer.parseInt("myString"); Commented May 2, 2014 at 11:28
  • possible duplicate of Converting a string to an integer on Android Commented May 2, 2014 at 11:39
  • Mix my comment with @smagnan and looks like a quick and easy to me :P Commented May 2, 2014 at 11:55
  • yes @smagnam I tried this but I am not getting exact sorting. Commented May 2, 2014 at 12:14

2 Answers 2

3

Either make your AllSpeeds data structure return an int (or double, or something else numeric) from getSpeed(), or use Integer.parse(string) on the two strings and then compare the integers.

Sign up to request clarification or add additional context in comments.

4 Comments

like this int firstSpeed = Integer.parseInt(lhs.getSpeed()); int secondSpeed = Integer.parseInt(rhs.getSpeed());
And I am comparing this 2 Inegers like this if (firstSpeed < secondSpeed) { return firstSpeed; } else { return secondSpeed; }
But it always executing else block only.
you can return firstSpeed - secondSpeed.
2

How about this

@Override
public int compare(AllSpeeds lhs, AllSpeeds rhs) {
    // TODO Auto-generated method stub      
    int a = Integer.parseInt(lhs.getSpeed());
    int b = Integer.parseInt(rhs.getSpeed());
    return a < b ? 1 : (a == b ? 0 : -1);
}

2 Comments

that return method giving "Cannot cast from String to Integer" error.Because my getSpeed() is String type.
Update one giving "Cannot invoke compareTo(int) on the primitive type int"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.