我在尝试解决或为我必须完成的任务提出解决方案时遇到了一些麻烦。
我正在尝试为我的应用程序制作排名系统。我的主缓存数据结构如下:
Map<String user, Profile personsProfile>
配置文件有许多值 - 其中一个是我想要排序的数值。配置文件类有一个自定义比较器:
public static class CompareHots implements Comparator<Profile> {
@Override
public int compare(Profile o1, Profile o2) {
return ((Integer) o1.getHots()).compareTo((Integer) o2.getHots());
}
}
就目前而言,给定一个列表(map.values())
我可以订购个人资料对象,但我没有办法将其绑定回用户。所以,例如,如果我想找到我可以做的配置文件john的排名
Collections.sort(cache.values(), new Profile.CompareHots)
然而,虽然这很快,但我需要通过迭代整个列表检查if(profile.getUserId().equals("John")
然后返回索引来撤消所有好的工作。
有谁知道我能解决这个问题的更好方法吗?
由于
答案 0 :(得分:1)
如果我正确理解您的用例,您希望找到按其个人资料排名排序的用户。如何更改映射:
Map<String user, Profile personsProfile>
为:
Map<Profile personsProfile, String user>
代替?现在,SortedMap的每个实现都将满足您的需求。当对键(它们是配置文件)进行迭代时,您可以按照Comparator提供的顺序获取它们。比使用配置文件并查找用户。就是这样。
答案 1 :(得分:0)
可能TreeMap会帮助您:
SortedMap<String, Profile> ranking = new TreeMap<>(customComparator);
...
String user = "John";
int rank = ranking.headMap(user, true).size();