如何在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); // 输出:

结果

相关推荐
动词ing12 分钟前
【C语言】自定义函数+指针入门
c语言·开发语言·算法
重生之后端学习26 分钟前
283. 移动零[简单]✅
开发语言·数据结构·算法·leetcode·职场和发展
吠品41 分钟前
Wine 在 Linux 上运行 Windows 软件完整指南
java·linux·服务器
动词ing1 小时前
【C语言】结构体+文件基础
c语言·开发语言·数据结构
caimouse2 小时前
ReactOS 窗口系统分析(7):分层窗口与绘制辅助 — layered.c + draw.c
c语言·开发语言
亚历克斯神2 小时前
智能搜索系统的升级复盘——从 Elasticsearch 到混合检索的检索质量提升
java·spring·微服务
丰锋ff2 小时前
基于 Qt 的智慧社区物业管理系统
开发语言·qt
夜不会漫长2 小时前
C++入门(1)
开发语言·c++·算法
大鹏说大话2 小时前
从爬虫到决策引擎:大数据下自媒体如何用Python挖掘用户痛点
开发语言·爬虫·python
Niuguangshuo2 小时前
silero-vad:超轻量级开源 VAD 实践指南
开发语言·python