I have class (JavaBean if you want to call it like that)
class Tweet{
private millis; //number of millis since 1970
//other attributes and getters and setters, but i want to sort onlny by millis
public long getMillis() {
return millis;
}
}
Comparator should be probably look simillar to this:
class TweetComparator implements Comparator {
@Override
public int compare(Tweet t1, Tweet t2) {
//something
//this doesn't work
//return t2.getMillis().compareTo(t1.getMillis());
return ??;//what should be here?
}
}
This will be in program
List<Tweet> tweets = new ArrayList<Tweet>();
tweets.add(...); //just fill the list
//i need newest (with hightest millis value first) so I probably need to call reverse order
Collection.reverse(tweets)
Collection.sort(tweets, new TweetComparator());
I found some references here and here. But I don't know how to complete my code.
Your comparator should look similar to this
class TweetComparator implements Comparator<Tweet> {
@Override
public int compare(Tweet t1, Tweet t2) {
return Long.compare(t1.getMillis(), t2.getMillis());
}
}
note that static int Long.compare is since Java 7
Compare method Returns: a negative integer, zero, or a positive integer as the first argument is less than, equal to, >or greater than the second.
Logic -
if t1.millis > t2.millis
return -1;
else if t1.millis < t2.millis
return +1;
Code -
class TweetComparator implements Comparator<Tweet> {
@Override
public int compare(Tweet t1, Tweet t2) {
if(s1.i>s2.i)
return -1;
else if(s1.i<s2.i)
return +1;
return 0;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With