假如我有两个有序集合(插入顺序很重要,而且我需要忽略重复项LinkedHashSet),其中一个集合中的第 n 个元素与另一个集合中的第 n 个元素配对。但它们不是成对添加的,而是最终结果会是成对的。
例如,在下面的代码中5,会与 配对1.1f,3也会与 配对0.5f
java
LinkedHashSet<Integer> slotIDs = new LinkedHashSet<>();
LinkedHashSet<Float> pitches = new LinkedHashSet<>();
// 模拟数据添加过程
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);
我想根据slotIDs配对结果pitches从低到高排序。在上面的例子中,我想要这样的结果:[3, 4, 5, 2, 1]
java
// 1. 将Set转换为List,以便通过索引访问
List<Integer> slotIDList = new ArrayList<>(slotIDs);
List<Float> pitchList = new ArrayList<>(pitches);
// 2. 确定有效配对的数量(以较短的列表为准)
int pairCount = Math.min(slotIDList.size(), pitchList.size());
// 3. 创建一个包含索引的列表 [0, 1, 2, ...],并根据对应的pitch值进行排序
List<Integer> sortedIndices = IntStream.range(0, pairCount)
.boxed()
.sorted(Comparator.comparing(pitchList::get))
.collect(Collectors.toList());
// 4. 根据排序后的索引,构建最终的slotID列表
List<Integer> result = sortedIndices.stream()
.map(slotIDList::get)
.collect(Collectors.toList());
// --- 核心逻辑结束 ---
System.out.println(result); // 输出:
结果
