Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort arrayList<Object> by object attribute long in Java

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.

like image 566
user1097772 Avatar asked Sep 29 '26 04:09

user1097772


2 Answers

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

like image 132
Evgeniy Dorofeev Avatar answered Oct 01 '26 17:10

Evgeniy Dorofeev


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;
     }

 }
like image 26
Subhrajyoti Majumder Avatar answered Oct 01 '26 19:10

Subhrajyoti Majumder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!