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

结果

相关推荐
IT小白杨3 小时前
从环境制备到自动化工作流:多账号运营的工程化架构拆解
java·经验分享·自动化·安全架构·指纹浏览器
豆瓣鸡4 小时前
算法日记 - Day3
java·开发语言·算法
萧瑟余晖4 小时前
Java深入解析篇九之NIO详解
java·网络·nio
韭菜炒鸡肝天4 小时前
VTK开发笔记(一):VTK介绍,Qt..+VSx+VTK.编译
开发语言·笔记·qt
The Chosen One9854 小时前
高进度算法模板速记(待完善)
java·前端·算法
Aaron - Wistron5 小时前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
Dxy12393102166 小时前
Python项目打包成EXE完整教程(PyInstaller实战避坑)
开发语言·python
0566466 小时前
Python康复训练——常用标准库
开发语言·python·学习
极光代码工作室6 小时前
基于SpringBoot的课程预约系统
java·springboot·web开发·后端开发
骊城英雄6 小时前
基于C#+avalonia ui实现的跨平台点胶机灌胶监控控制上位机软件
开发语言·ui·c#