如何使用Java中另一个对象的属性对对象列表进行排序?

Rag*_*thy 5 java sorting collections comparator

我有两个包含两种不同类型对象的列表。

  1. 协议(obj1)
  2. 传感器(obj2)

使用比较器使用“Collections.sort”根据属性(protocolId)对协议列表进行排序。现在协议和传感器对象都具有相同的属性,称为“referenceName”。由于第一个列表(协议)已排序,我希望使用属性“referenceName”按照协议列表的相同顺序对第二个列表(传感器)进行排序。

由于 Comparator 只能比较同一列表中的两个对象。我在比较第一个列表和第二个列表时遇到问题。有人可以帮我吗?

Flo*_*yle 2

referenceName您可以使用 Java 8 lambda 在 a及其在排序列表中的索引之间创建映射Protocol

public class Protocol {
    final String referenceName;

    public String getReferenceName() {
        return referenceName;
    }

    // other stuff
}

public class Sensor {
    final String referenceName;

    public String getReferenceName() {
        return referenceName;
    }

    // other stuff
}
Run Code Online (Sandbox Code Playgroud)
final List<Protocol> protocols = getProtocols();
final List<Sensor> sensors = getSensors();

// TODO : sort protocols here

// create a mapping between a referenceName and its index in protocols
final Map<String, Integer> referenceNameIndexesMap = IntStream.range(0, protocols.size()).mapToObj(i -> i)
            .collect(Collectors.toMap(i -> protocols.get(i).getReferenceName(), i -> i));

// sort sensors using this mapping
sensors.sort(Comparator.comparing(s -> referenceNameIndexesMap.get(s.getReferenceName())));

// sensors is now sorted in the same order of referenceName as protocols
Run Code Online (Sandbox Code Playgroud)