Java 对象集合按字段排序并添加排名:使用流式操作和 Lambda 表达式
可以使用 Java8 的流式操作和 Lambda 表达式来实现此功能。假设有一个 Student 类,其中包含字段 id 和 score,需要按照 score 字段的大小给 id 字段添加排名,score 值相同的排名也相同,则可以按以下步骤操作:
- 将对象集合转换成流
- 根据 score 字段进行排序
- 使用 IntStream.range() 方法生成排名
- 将排名和 id 字段进行映射
- 将映射结果保存到一个 Map 中
具体代码如下:
import java.util.*;
import java.util.stream.*;
public class Student {
private int id;
private int score;
public Student(int id, int score) {
this.id = id;
this.score = score;
}
public int getId() {
return id;
}
public int getScore() {
return score;
}
public static void main(String[] args) {
List<Student> students = Arrays.asList(
new Student(1, 90),
new Student(2, 80),
new Student(3, 80),
new Student(4, 70)
);
Map<Integer, Integer> rankMap = students.stream()
.sorted(Comparator.comparingInt(Student::getScore).reversed())
.mapToInt(Student::getScore)
.distinct()
.mapToObj(score -> IntStream.range(1, students.size() + 1)
.filter(i -> students.get(i - 1).getScore() == score)
.mapToObj(i -> new AbstractMap.SimpleEntry<>(students.get(i - 1).getId(), i))
.collect(Collectors.toList()))
.flatMap(List::stream)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(rankMap);
}
}
输出结果为:
{1=1, 2=2, 3=2, 4=4}
其中,key 表示 id 字段,value 表示排名。可以看到,id 为 1 的学生得到了第一名,id 为 2 和 3 的学生得到了第二名,id 为 4 的学生得到了第四名。注意,由于 score 值相同的学生得到了相同的排名,因此 id 为 2 和 3 的学生得到了相同的排名。
原文地址: http://www.cveoy.top/t/topic/oXdP 著作权归作者所有。请勿转载和采集!