'Comparator - int cannot be dereferenced [duplicate]
I saw an example on here how to sort an ArrayList using the Comparator interface, so I tried it out. With Strings it worked perfectly, but with one variable that I want to sort being an Integer, it will not compile, saying "int cannot be dereferenced".
What can I do so that this will work and allow me to sort an ArrayList by the score variable?
Here's my code:
public class ScoreComparator implements Comparator<Review> {
@Override
public int compare(Review o1, Review o2)
{
return o1.getScore().compareTo(o2.getScore());
}
}
Solution 1:[1]
Fyi, although this doesn't answer your specific question about the int dereferencing error, in Java 8 you don't need the dedicated comparator class at all. You can simply write:
yourList.sort((r1, r2) -> Integer.compare(r1.getScore(), r2.getScore()));
or
yourList.sort(Comparator.comparingInt(Review::getScore));
both of which are much nicer ways to do it.
Solution 2:[2]
try this:
public class ScoreComparator implements Comparator<Review> {
@Override
public int compare(Review o1, Review o2)
{
return (o1.getScore()<o2.getScore() ? -1 : (o1.getScore()==o2.getScore() ? 0 : 1));
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Boann |
| Solution 2 | Joel |
