0

I need to sort an ArrayList by a certain value.

In this case, the list object getUsers23 is a String, but I need to compare that value as double.

Example value or getUser23 = "67.455432434234"

At the moment, using Collections.sort() to sort the arrayList is sorting the arrayList by getUser23 as string value:

  Collections.sort(spotsList1, new Comparator<Spots>(){
            public int compare(Spots obj1, Spots obj2) {

                return obj1.getUsers23().compareToIgnoreCase(obj2.getUsers23()); 

            }
        });
5
  • Your question is not clear. Do you have 67.455432434234 stored against getUser23 in your object? Commented Mar 31, 2020 at 15:44
  • @RajenRaiyarela, yes but as string value Commented Mar 31, 2020 at 15:45
  • If you have getter for that then you can do Double.valueOf("67.455432434234") or Double.parseDouble("67.455432434234") as @Farid mentioned to convert to double and then compare Commented Mar 31, 2020 at 15:46
  • convert the string to double using 'Double.parseDouble(getUsers23())' then compare them Commented Mar 31, 2020 at 15:46
  • @RajenRaiyarela. just before the return or inside the return? Commented Mar 31, 2020 at 15:47

1 Answer 1

1

You can convert to double and then compare.

Modify your code inside comparator as

try{
    return Double.valueOf(obj1.getUsers23()).compareTo(Double.valueOf(obj2.getUsers23()));
}catch (Exception e){
   return -1;
} 
Sign up to request clarification or add additional context in comments.

1 Comment

let me try it out

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.