0

I am trying to compare two lists of objects when they are mix up. I have a class Sms and another class ArchivedSms extends Sms.

How to compare List of these objects using Collections.sort(collection, comparator) ?

List<Sms> smses = new ArrayList<Sms>();
List<ArchivedSms> archivedSmses = new ArrayList<ArchivedSms>();

smses.addAll(archivedSmses);

How to compare these objects assume they have both same fields, so I would like to compare for example phoneNumbers which are strings.

Avi
  • 21,182
  • 26
  • 82
  • 121
Przemek85
  • 171
  • 1
  • 1
  • 10

1 Answers1

3

You should write your own comparator that implements Comparator<Sms>

public class SmsComparator implements `Comparator<Sms>` {
    @Override
    public bool compare(Sms o1, Sms o2) {
       // Implement comparison logic
    }
 }

Let's assume each Sms instance has a field int a so the comparator would look something like this:

public class SmsComparator implements `Comparator<Sms>` {
    @Override
    public bool compare(Sms o1, Sms o2) {
       if(o1.getA() > o2.getA()) return 1;
       else if(o1.getA() > o2.getA()) return -1;
       else return 0;
    }
 }

You can do the same inline when calling Collections.sort:

Collections.sort(smes, new Comparator<Sms>() {
   @Override
    public bool compare(Sms o1, Sms o2) {
       if(o1.getA() > o2.getA()) return 1;
       else if(o1.getA() > o2.getA()) return -1;
       else return 0;
    }
})

And in java 8 you can do the same as a lambda function (because that's a functional interface).

Avi
  • 21,182
  • 26
  • 82
  • 121
  • can't I user inline new Comparator ? for example Collections.sort(smses, new Comparator(){}); – Przemek85 Feb 10 '16 at 13:16
  • Sure, just implement the `compare` method inline. In java 8 this can also be a lambda expression because that's a functional interface. – Avi Feb 10 '16 at 13:17
  • I wrote @Override public int compare(Sms o1, Sms o2) { if (o1.getPhoneNumber().equals(o2.getPhoneNumber())) { return 1; } else if (!(o1.getPhoneNumber().equals(o2.getPhoneNumber()))) { return -1; } else return 0; } but it still not working @Collections.sort(smses, new SmsComparator()); is it okey to compare here Sms and ArchivedSms class ? – Przemek85 Feb 10 '16 at 13:21