Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort list of objects with a property of another object in Java?

I have two lists which holds two different types of objects.

  1. Protocol(obj1)
  2. Sensor(obj2)

Protocol list is sorted based on a property(protocolId) using "Collections.sort" using comparator. Now both Protocol and Sensor objects has same property called "referenceName". Since the first list(protocol) is sorted, I want the second list(Sensor) to be sorted in the same order of the Protocol list using the property "referenceName".

Since the Comparator can only compare two objects with in the same list. I am facing problems with comparing the first list with the second. Could somebody help me out?

like image 870
Ragupathy Avatar asked May 16 '17 06:05

Ragupathy


1 Answers

Why don't you have a new class that holds both Protocol and Sensor with particular referenceName and sort that. Following is the pseudo-code of the class -

class ProtocolSensorGroup implements Comparable {
  private String referenceName;
  private Protocol protocol;
  private Sensor sensor;

  public boolean compareTo(ProtocolSensorGroup lhs, ProtocolSensorGroup rhs) {
    String pidLhs = lhs.getProtocol().getId();
    String pidRhs = rhs.getProtocol().getId();

    return pidLhs.compareTo(pidRhs); // Or your logic here
  }
}
like image 172
jaibatrik Avatar answered Oct 07 '22 19:10

jaibatrik