gpt4 book ai didi

java - 如何使用特定的类属性对 arraylist asc 进行排序?

转载 作者:行者123 更新时间:2023-12-01 22:18:30 25 4
gpt4 key购买 nike

我有一个带有我的类配置文件(名称和评级)的 ArrayList,我需要在我的 Arraylist 中订购此信息以获取评级属性。

例如:

  • 姓名:约翰评分:50
  • 姓名:米歇尔评分:30
  • 姓名:Petter 评分:55
  • 姓名:基督徒评分:78
  • 姓名:Seba 评分:60

我需要这个:

  • 姓名:约翰·米歇尔:30
  • 姓名:约翰评分:50
  • 姓名:Petter 评分:55
  • 姓名:Seba 评分:60
  • 姓名:基督徒评分:78

最后我想获得最佳评价:

  • 姓名:基督徒评分:78

我的类(class)简介:

public class Profile {
private String name;
private int rated;

public Profile(String name,int rated) {
this.name=name;
this.rated=rated;

}

public String getName(){
return name;
}
public int getrated(){
return rated;

}


}

我正在尝试这个,它不起作用:

ArrayList<Profile> aLprofile=new ArrayList<Profile>();
aLprofile.sort(aLprofile.get(0).getrated());

您有其他方法或任何提示给我。

最佳答案

您需要将比较器传递给排序方法。因此,通过提供您想要与 Profile 实例进行比较的逻辑来使用 Comparator.comparingInt

所以在你的情况下:

comparingInt(p1 -> p1.getRated());

可以用方法引用替换:

aLprofile.sort(comparingInt(Profile::getRated));

<小时/>但如果你只想获取最大值,则无需排序,可以使用 Collections.max:

Profile p = Collections.max(aLprofile, comparingInt(Profile::getRated));

关于java - 如何使用特定的类属性对 arraylist asc 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30445487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com