
本文详细介绍了如何在Java中对一组数值型评级数据进行排序,并同时保留其原始输入顺序(如'Rate 1', 'Rate 2'等),从而准确识别最高和最低评级及其对应的原始标签。我们将利用Java Stream API,结合自定义比较器,高效地实现这一需求,避免直接修改原始数据顺序。
在许多数据处理场景中,我们经常需要对一组数值进行排序,并找出其中的最大值和最小值。然而,一个常见的挑战是,在排序过程中如何保留原始数据项的上下文信息,例如它们的原始标签或索引。例如,当我们需要对一系列“评级”进行排序时,仅仅输出排序后的数值是不够的,我们还需要知道哪个“Rate X”对应哪个值,以及哪个“Rate X”是最高或最低的。
假设我们有一组评级数据,如 Rate 1: 237, Rate 2: 4303, Rate 3: -635 等。我们的目标是:
一个直观但存在局限性的方法是,将所有评级值存储到一个数组中,然后直接对该数组进行排序。例如,使用冒泡排序:
立即学习“Java免费学习笔记(深入)”;
// 假设 arr 存储了评级值
int[] arr = {237, 4303, -635, 715, 56};
// ... 冒泡排序代码 ...
// 排序后 arr 变为 {-635, 56, 237, 715, 4303} 或其逆序
// 此时,我们无法直接知道 4303 对应的是 Rate 2,237 对应的是 Rate 1这种方法的问题在于,一旦数组被排序,原始值与其在数组中的原始位置(即“Rate X”的X)之间的关联就丢失了。为了解决这个问题,我们需要一种机制来在排序的同时,保留这种原始索引信息。
Java 8引入的Stream API提供了一种强大而灵活的方式来处理集合数据。我们可以利用它来创建一个索引流,然后根据原始数组中的值来排序这些索引,从而达到既排序了值又保留了原始索引的目的。
核心思路是:
以下是实现此逻辑的Java代码示例:
import java.util.Comparator;
import java.util.stream.IntStream;
public class RatingSorter {
/**
* 对输入的评级数组进行排序,并输出从高到低的评级及其原始标签,
* 同时标识最高和最低评级。
*
* @param input 包含评级数值的整数数组。
*/
static void highestToLowestOrder(int[] input) {
int length = input.length;
// 1. 创建一个包含原始索引的流 (0, 1, 2, ..., length-1)
// 2. 将整数索引装箱为 Integer 对象,以便进行对象流操作
// 3. 使用自定义比较器对这些索引进行排序:
// 比较器 i -> input[i] 表示根据原始数组中索引 i 对应的值进行比较
// .reversed() 表示降序排序 (从高到低)
// 4. 将排序后的 Integer 索引流映射回 int 类型
// 5. 收集结果到一个新的 int 数组 ordered 中
// ordered 数组现在存储的是原始索引,这些索引按照它们在 input 数组中对应值的大小从高到低排列
int[] ordered = IntStream.range(0, length)
.boxed()
.sorted(Comparator.comparingInt(i -> input[i]).reversed())
.mapToInt(Integer::intValue)
.toArray();
System.out.println("Ratings in Highest to Lowest order :");
System.out.println();
// 遍历 ordered 数组,输出排序后的评级及其原始标签
// ordered[i] 是一个原始索引,所以 "Rate" 后面是 ordered[i] + 1
IntStream.of(ordered)
.forEach(originalIndex -> System.out.printf("Rate %d%n", originalIndex + 1));
System.out.println();
// 识别最高评级:ordered[0] 存储的是最高评级对应的原始索引
int highestRatingOriginalIndex = ordered[0];
System.out.printf("The Highest Rating is Rate %d with the of %d%n",
highestRatingOriginalIndex + 1, input[highestRatingOriginalIndex]);
// 识别最低评级:ordered[length - 1] 存储的是最低评级对应的原始索引
int lowestRatingOriginalIndex = ordered[length - 1];
System.out.printf("The Lowest Rating is Rate %d with the of %d%n",
lowestRatingOriginalIndex + 1, input[lowestRatingOriginalIndex]);
}
public static void main(String[] args) {
// 测试用例
int[] inputRatings = {237, 4303, -635, 715, 56};
highestToLowestOrder(inputRatings);
}
}使用上述代码和提供的测试用例 int[] inputRatings = {237, 4303, -635, 715, 56};,程序将生成以下输出:
Ratings in Highest to Lowest order : Rate 2 Rate 4 Rate 1 Rate 5 Rate 3 The Highest Rating is Rate 2 with the of 4303 The Lowest Rating is Rate 3 with the of -635
通过上述方法,我们不仅能够对数值数据进行灵活排序,还能有效保留其原始上下文信息,这在数据分析和报告生成中至关重要。
以上就是Java教程:高效排序数值并保留原始索引信息的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号