我想根据他们的分数对一些替代品进行排名,并打印每个替代品的名称及其排名,我该怎么做?
这是MWE:
import java.util.Arrays;
public class Ranking {
public static void main(String[] args) {
//The score of the alternatives :
double [] score = new double [4] ;
score[0] = 6.75 ;
score[1] = 9.0 ;
score[2] = 6.75 ;
score[3] = 5.50;
//The name of the alternatives :
String [] name = new String [4] ;
name[0] = "a1";
name[1] = "a2";
name[2] = "a3";
name[3] = "a4";
//Descending Sorting the score array like this :
for(int i=0;i<4;i++)
score[i]= - score[i];
Arrays.sort(score);
for(int i=0;i<4;i++)
score[i]= - score[i];
//print the result
for(int i=0;i<4;i++)
System.out.println(score[i] + " rank = " + (i+1));
}
//result :
//9.0 rank = 1
//6.75 rank = 2
//6.75 rank = 3
//5.5 rank = 4
但我想要这样的结果:
name : a2 a1 a3 a4
rank : 1 2 3 4
我该怎么做?
答案 0 :(得分:1)
您对单个数组进行排序,因此无法在名称 - 等级之间映射结果。
在java中,通常的方法是将数据抽象为对象并对其进行操作:
声明你的模型类:
public YourModel {
private String name;
private double score;
public Rank(String name, double score) {
this.name = name;
this.score = score;
}
// you create your getters/ setters
}
向数组中添加数据:
YourModel[] models = new YourModel[4];
models[0] = new YourModel("a1", 6.75D);
...添加其他型号......
对数组进行排序:
Arrays.sort(models, Comparator.comparing(YourModel::getScore));
完成此步骤后,您将对数组进行排序:
[{"a2", 9.0} ....]
您可以打印结果:
for(int i=0;i<4;i++)
System.out.println(models[i].getName() + " rank = " + (i+1));
}
答案 1 :(得分:1)
您应该使用Map<String, Double>
。
尝试以下示例:
Map<String, Double> map = new HashMap<>();
map.put("a1", 6.75);
map.put("a2", 9.0);
map.put("a3", 6.8);
map = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(
Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
//Iterate through the map
您将以反向排序的顺序得到答案。
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
用于按值排序,LinkedHashMap::new
用于维护Map
的排序
答案 2 :(得分:1)
当您必须对某些内容进行排序时,您应该查看TreeSet
或TreeMap
结构。实际上Array
不是排序是主要功能的地方。
您似乎对所有对象都有唯一的names
,那么您必须将TreeSet
与reverce比较器一起使用。因此,当您遍历Set
时,您将获得所需的订单:
final class Model {
private final String name;
private final double score;
public Model(String name, double score) {
this.name = name;
this.score = score;
}
}
final Comparator<Model> reverceScore = (d1, d2) -> {
if (d1.name.equalsIgnoreCase(d2.name))
return 0;
int res = Double.compare(d2.score, d1.score);
return res != 0 ? res : d1.name.compareTo(d2.name);
};
Set<Model> data = new TreeSet<>(reverceScore);
data.add(new Model("a1", 6.75));
data.add(new Model("a2", 9));
data.add(new Model("a3", 6.75));
data.add(new Model("a4", 5.5));
int rank = 1;
for(Model model : data)
System.out.println("rank: " + rank++ + " - name: " + model.name + ", score: " + model.score);