如何在Java中根据另一组成对数据对一个集合进行排序?

后端开发 2026-07-11

我有两个有序集合(插入顺序很重要且需要忽略重复项,因此 LinkedHashSet),其中一个集合的第n 个元素与另一个集合的第n 个元素成对。但它们并不是按成对的形式被加入,最终的结果才会成对。

例如,在下面的代码 5 将与 1.1f 配对,3 将与 0.5f 配对:

LinkedHashSet<Integer> slotIDs = new LinkedHashSet<>();
LinkedHashSet<Float> pitches = new LinkedHashSet<>();
// example additions over time
slotIDs.add(3);
slotIDs.add(1);
slotIDs.add(2);
pitches.add(0.5f);
pitches.add(2.2f);
slotIDs.add(5);
slotIDs.add(2);
pitches.add(1.3f);
slotIDs.add(4);
pitches.add(1.1f);
pitches.add(1.3f);
pitches.add(0.7f);
slotIDs.add(5);
pitches.add(1.1f);

并且我想根据它们配对的 pitches,把 slotIDs 从低到高排序。在上面的示例中,我希望得到的结果是:[3, 4, 5, 2, 1]。实现这个的最佳方法是什么?

解决方案

因为 SetHashSetLinkedHashSet 除了通过插入顺序之外很难把项联系起来,因此我做的第一件事就是建立一个真正的映射关系。

record SlotIDAndPitch(int slotID, float pitch) {}

List<SlotIDAndPitch> combined = new ArrayList<>();
Iterator<Integer> slotIDIterator = slotIDs.iterator();
Iterator<Float> pitchIterator = pitches.iterator();
while (slotIDIterator.hasNext()) {
    combined.add(new SlotIDAndPitch(slotIDIterator.next(), pitchIterator.next()));
}

接着就很容易得到结果:

LinkedHashSet<Integer> sortedSlotIDs = combined.stream()
        .sorted(Comparator.comparingDouble(SlotIDAndPitch::pitch))
        .map(SlotIDAndPitch::slotID)
        .collect(Collectors.toCollection(LinkedHashSet::new));

注:这假设两个集合始终有匹配的条目。如果向其中一个集合添加失败但另一个集合添加成功,前面的合并步骤就会出错。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章