按对象变量对对象的LinkedList进行排序 [英] Sort a LinkedList of objects by object's variable

查看:287
本文介绍了按对象变量对对象的LinkedList进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题,我有一个LinkedList对象,这些对象具有String名称和int得分值.

Here is my problem, I have a LinkedList of objects, which have a String name and an int score value.

现在,我需要根据得分值对列表进行降序排序.

Now, I need to sort this list in descending order based on the score value.

我该怎么做?我尝试使用Collections.sort(List),但这不适用于对象.

How do I do that? I tried with Collections.sort(List), but that doesn't work with objects.

如何告诉Java将分数用作比较的值?

How do I tell Java to use the score as the value to comparison?

推荐答案

Collections.sort方法接受比较器作为第二个参数. 您可以传入定义所需顺序的比较器. 例如,给定一个Person类:

The Collections.sort method accepts a comparator as its second argument. You can pass in a comparator that defines the ordering that you want. For example given a Person class:

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与自定义比较器结合使用,按分数的降序对人员进行排序,如下所示:

You can use Collections.sort with a custom comparator to sort Persons by descending order of score like this:

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}]

这篇关于按对象变量对对象的LinkedList进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆