Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list of objects using Collection.sort() with lambdas only

I am beginner in lambdas and trying to understand how it works. So I have this list of Student with id and score attributes and I have to sort it accoding to the score . My Code

import java.util.*;

class Student {

    int id, score;

    public Student(int id, int score) {
        this.id = id;
        this.score = score;
    }
    public String toString() {
        return this.id + " " + this.score;
    }
}

interface StudentFactory < S extends Student > {
    S create(int id, int score);
}

class Test {

    public static void main(String[] ad) {

        StudentFactory < Student > studentFactory = Student::new;
        Student person1 = studentFactory.create(1, 45);
        Student person2 = studentFactory.create(2, 5);
        Student person3 = studentFactory.create(3, 23);

        List < Student > personList = Arrays.asList(person1, person2, person3);

         // error in the below line
        Collections.sort(personList, (a, b) -> (a.score).compareTo(b.score));
        System.out.println(personList);
    }
}

as you can see I tried Collections.sort(personList, (a, b) -> (a.score).compareTo(b.score)); it gave me error int cannot be dereferenced I know the error expected I just want to show what I wanted.
So is there any way to sort the Student object accoding to score using lambdas only?
I have also seen similar post where I found that List.sort or BeanComparator is the other option but is there any way I can do it with lambdas?
Thanks

like image 725
singhakash Avatar asked Oct 12 '15 19:10

singhakash


1 Answers

(a, b) -> Integer.compare(a.score, b.score)

would work. int is not an object, it is a primitive, and you can't call int.compareTo, or any other methods on int.

Even better than that would be

Comparator.comparingInt(s -> s.score)

or, with a getter,

Comparator.comparingInt(Student::getScore)

And using List.sort doesn't make a difference as to whether or not you use lambdas or whatever. You just write personList.sort(Comparator.comparingInt(s -> s.score)) instead of Collections.sort(personList, Comparator.comparingInt(s -> s.score)).

like image 77
Louis Wasserman Avatar answered Sep 25 '22 09:09

Louis Wasserman