Can I use compareTo to sort integer and double values? My system gives me an error that I Cannot invoke compareTo(int) on the primitive type int. any ideas?
Code:
Step 1: Sort list by last name (for String values)
Collections.sort(peopleList, (p1, p2) ->
p1.getLastName().compareTo(p2.getLastName()));
Step 2: Print all elements in the list
for (People ppl : peopleList) {
System.out.print(ppl.getFirstName()+" - "+ppl.getLastName());
}
Step 1: Sort list by Age (for int values)
Collections.sort(peopleList, (p1, p2) -> p1.getAge() - (p2.getAge()));
Step 2: Print all elements in the list
for (People ppl : peopleList) {
System.out.println(ppl.getAge());
}
Well, the compiler's right :) You can't call compareTo
directly. However, depending on the version of Java you're using, you can use Integer.compare (introduced in 1.7) and Double.compare (introduced in 1.4).
For example:
return Integer.compare(o1C.getPrice(), o2C.getPrice());
If you're not on 1.7 and still want to use built-in methods, you could use:
Integer price1 = o1C.getPrice();
Integer price2 = o2C.getPrice();
return price1.compareTo(price2);
... but this will use unnecessary boxing. Given that sorting a large collection can perform really quite a lot of comparisons, that's not ideal. It may be worth rewriting compare
yourself, until you're ready to use 1.7. It's dead simple:
public static int compare(int x, int y) {
return x < y ? -1
: x > y ? 1
: 0;
}
Change the code
int price;
to
Integer price;
because primitive types such as int
will not support any methods, like compareTo()
.
In your current code; easier solution would be to just change this line and all will be good:
return o1C.getPrice() - o2C.getPrice() ;
This would work fine and good performance too because method compare() has only following requirement viz. return zero if both values are equal; else a positive/negative number.