问题描述
说我有以下简单的数据结构。
Say I have following simple data structure.
public class Player {
private Long id;
private String name;
private Integer scores;
//getter setter
}
到目前为止一切顺利。现在的问题是,我如何获得球员排名?
我有另一种排名数据结构,即 -
So far so good. Now question is , how do I get what's a players rank?I have another data structure for ranking, that is-
public class Ranking {
private Integer score;
private Integer rank;
//getter/setter
}
所以我有一个播放器列表,我想计算一个排名列表,我想使用java8 stream api。
So I have a list of player and i want to compute a list of ranking and I would like to use java8 stream api.
我有一个名为<$ c的服务$ c> PlayerService 如下:
public class PlayerService {
@Autowired
private PlayerRepository playerRepository;
public List<Ranking> findAllRanking(Long limit) {
List<Player> players = playerRepository.findAll();
// calculation
return null;
}
计算很简单,得分最高的人排名最高。
The calculation is simple, whoever has most score has most ranking.
如果我有 5,7,8,9,3
分数,那么排名将是
If I have 5,7,8,9,3
scores then ranking would be
rank score
1 9
2 8
3 7
4 5
5 3
任何帮助将不胜感激。
Any help would be appreciated.
推荐答案
试试这个:
List<Player> players = new ArrayList<Player>() {{
add(new Player(1L, "a", 5));
add(new Player(2L, "b", 7));
add(new Player(3L, "c", 8));
add(new Player(4L, "d", 9));
add(new Player(5L, "e", 3));
add(new Player(6L, "f", 8));
}};
int[] score = {Integer.MIN_VALUE};
int[] no = {0};
int[] rank = {0};
List<Ranking> ranking = players.stream()
.sorted((a, b) -> b.getScores() - a.getScores())
.map(p -> {
++no[0];
if (score[0] != p.getScores()) rank[0] = no[0];
return new Ranking(rank[0], score[0] = p.getScores());
})
// .distinct() // if you want to remove duplicate rankings.
.collect(Collectors.toList());
System.out.println(ranking);
// result:
// rank=1, score=9
// rank=2, score=8
// rank=2, score=8
// rank=4, score=7
// rank=5, score=5
// rank=6, score=3
变量得分
,否
和 rank
是 .map()
中lambda函数中的自由变量。所以不能重新分配它们。如果它们的类型是 int
而不是 int []
,则无法编译代码。
The variables score
, no
and rank
are free variables in the lambda function in .map()
. So they must not be reassigned. If their types are int
instead of int[]
, you cannot compile the code.
这篇关于如何从列表中计算玩家的等级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!