这是我的问题。按对象的变量对对象的LinkedList进行排序
我有一个LinkedList
的对象,它们有一个字符串名称和一个int分数值。
现在我需要根据得分值以降序对这个列表进行排序。
我该怎么做?我试着用Collections.sort(List),但这不适用于对象。
如何告诉java使用分数作为比较值?
这是我的问题。按对象的变量对对象的LinkedList进行排序
我有一个LinkedList
的对象,它们有一个字符串名称和一个int分数值。
现在我需要根据得分值以降序对这个列表进行排序。
我该怎么做?我试着用Collections.sort(List),但这不适用于对象。
如何告诉java使用分数作为比较值?
的Collections.sort
方法接受一个比较器作为其第二个论点。 您可以传入一个比较器来定义所需的顺序。 例如给予Person
类:
class Person {
private final String name;
private final int score;
Person(String name, int score) {
this.name = name;
this.score = score;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", score=" + score +
'}';
}
}
可以使用Collections.sort
使用自定义比较的降序得分次序像这样的人进行排序:
List<Person> list = new LinkedList<>(Arrays.asList(new Person("Jack", 3), new Person("Mike", 9)));
System.out.println("before: " + list);
Collections.sort(list, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o2.score - o1.score;
}
});
System.out.println("after: " + list);
这将输出:
before: [Person{name='Jack', score=3}, Person{name='Mike', score=9}] after: [Person{name='Mike', score=9}, Person{name='Jack', score=3}]
谢谢! – John
Collections.sort(List)
作品Objects
只要Objects
媲美彼此既可以通过java.lang.Comparable
或java.util.Comparator
。既然你Objects
需要自定义排序,你需要实现一个比较
Collections.sort(list,new Comparator(){
@Override
public int compare(MyObject obj1,MyObject obj2){
return obj2.score - obj1.score;
}
});
随着其他的答案,这里是一个整洁的Java 8解决方案:
Collections.sort(list, Comparator.comparingInt(obj -> obj.score).reversed());
的reversed()
是降序排列,这对由obj.score
。
正如Iaune指出的,如果您正确使用Encapsulation,obj -> obj.score
可以替换为ObjType::getScore
。
你的意思是你有'''LinkedHashMap'''? LinkedList没有K,V对。 – Siddhartha
Collections.sort有一个可以通过比较器的版本。 http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator) –
我不(?)这个将是我第一次对列表进行排序,就像我以前使用阵列一样,所以我是一个新手。 Highschool高级,如果这给出了任何参考我对Java的了解程度如何 – John