如何在Java中根据另一个配对集合对一个集合进行排序

假如我有两个有序集合(插入顺序很重要,而且我需要忽略重复项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); // 输出:

结果

相关推荐
卷毛的技术笔记37 分钟前
告别硬编码!Spring AI Alibaba 实现 AI Agent 智能工具调用(Tool Calling)
java·人工智能·后端·python·spring·ai编程
编程大师哥37 分钟前
匿名函数 lambda + 高阶函数
java·python·算法
isyangli_blog39 分钟前
OpenDayLight (Carbon 版本) 启动与组件安装
开发语言·php
vb2008111 小时前
FastAPI APIRouter
开发语言·python
Benszen1 小时前
KVM虚拟化解决方案
开发语言·perl
会编程的土豆1 小时前
Go 语言反射(Reflection)详解
开发语言·后端·golang
東雪木1 小时前
多线程与并发编程 专属复习笔记
java·开发语言·笔记·java面试
adrninistrat0r1 小时前
Java调用链MCP分析工具
java·python·ai编程
杨充1 小时前
1.3 浮点型数据设计灵魂
开发语言·python·算法
噜噜噜阿鲁~1 小时前
python学习笔记 | 11.3、面向对象高级编程-多重继承
java·开发语言