Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a LinkedList of objects by object's variable [duplicate]

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.

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

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

like image 677
John Avatar asked Dec 19 '22 23:12

John


2 Answers

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 +
                '}';
    }
}

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);

This will output:

before: [Person{name='Jack', score=3}, Person{name='Mike', score=9}]
after: [Person{name='Mike', score=9}, Person{name='Jack', score=3}]
like image 168
janos Avatar answered Dec 25 '22 22:12

janos


Along with other answers, here is a neat Java 8 solution:

Collections.sort(list, Comparator.comparingInt(obj -> obj.score).reversed());

The reversed() is for descending order, and this compares by obj.score.

As noted by Iaune, obj -> obj.score can be replaced by ObjType::getScore if you are using Encapsulation correctly.

like image 31
bcsb1001 Avatar answered Dec 25 '22 22:12

bcsb1001