Sachin Handiekar
May 2019
M T W T F S S
« Jan    
 12345
6789101112
13141516171819
20212223242526
2728293031  

Categories


Java 8 :: Comparator Example

Sachin HandiekarSachin Handiekar

A code example showing the use of Comparator in Java 8 using Comparator.comparing method.

public class Student {

    private String name;
    private String subject;
    private double grade;

    public Student(String name, String subject, double grade) {
        this.name = name;
        this.subject = subject;
        this.grade = grade;
    }

    public String getName() {
        return name;
    }

    public String getSubject() {
        return subject;
    }

    public double getGrade() {
        return grade;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", subject='" + subject + '\'' +
                ", grade=" + grade +
                '}';
    }
}

We can use the Comparator.comparing method to sort the Java Object, also the method reveresed the comparison result.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class StudentExample {

    public static void main(String[] args) {
        List studentList = new ArrayList<>();

        studentList.add(new Student("Sachin", "English", 80.45));
        studentList.add(new Student("Raj", "Science", 70.12));
        studentList.add(new Student("Vikram", "Mathematics", 66.54));

        studentList.sort(Comparator.comparing(Student::getGrade)
                .reversed()
                .thenComparing(Student::getName)
                .thenComparing(Student::getSubject));

        System.out.println(studentList);
    }
}
Comments 0
There are currently no comments.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.