Java Comparator.comparing

By Arvind Rai, March 13, 2019
comparing is the static method of Comparator functional interface. Comparator.comparing method has been introduced in Java 8. Comparator.comparing accepts a Function that extracts a Comparable sort key from the given type and returns a Comparator that compares by that sort key. Comparator.comparing has two forms.
1.
static <T,U extends Comparable<? super U>> Comparator<T> comparing(Function<? super T,? extends U> keyExtractor) 
We need to pass a Function and it will extract a Comparable sort key from a type T, and will return a Comparator that compares by that sort key. Find the sample code.
Comparator<Student> nameComparator = Comparator.comparing(Student::getName); 
2.
static <T,U> Comparator<T> comparing(Function<? super T,? extends U> keyExtractor, Comparator<? super U> keyComparator) 
We need to pass a Function and a Comparator. The method will extract a sort key from a type T, and returns a Comparator that compares by that sort key using the specified Comparator. Find the sample code.
Comparator<Student> nameComparator = Comparator.comparing(Student::getName, (s1, s2) -> s2.compareTo(s1)); 
For the int, long and double datatype sort keys, Comparator has comparingInt, comparingLong and comparingDouble methods respectively.

Comparator.comparing

Here we will provide the examples of Comparator.comparing method. Find a class that will implement Comparable interface and define compareTo method.
School.java
package com.concretepage;
public class School implements Comparable<School> {
  private int code;
  private String sname;
  public School(int code, String sname) {
	this.code = code;
	this.sname = sname;
  }
  public int getCode() {
        return code;
  }
  public String getSname() {
        return sname;
  }
  @Override
  public int compareTo(School s) {
	return s.sname.compareTo(sname);
  }
} 
Create another class in which we will create class property of School type.
Student.java
package com.concretepage;
import java.util.Arrays;
import java.util.List;
public class Student {
  private String name;
  private int age;
  private long homeDistance;  
  private double weight;
  private School school;
  public Student(String name, int age, long homeDistance, double weight, School school) {
	this.name = name;
	this.age = age;
	this.homeDistance = homeDistance;
	this.weight = weight;
	this.school = school;
  }
  public String getName() {
        return name;
  }
  public int getAge() {
        return age;
  }
  public long getHomeDistance() {
        return homeDistance;
  }
  public double getWeight() {
        return weight;
  }
  public School getSchool() {
        return school;
  }
  public static List<Student> getStudentList() {
	Student s1 = new Student("Ram", 18, 3455, 60.75, new School(101, "PQ College"));
	Student s2 = new Student("Shyam", 22, 3252, 65.80, new School(103, "RS College"));
	Student s3 = new Student("Mohan", 19, 1459, 65.20, new School(102, "AB College"));
	Student s4 = new Student("Mahesh", 20, 4450, 70.25, new School(104, "CD College"));
	List<Student> list = Arrays.asList(s1, s2, s3, s4);
	return list;
  }
} 
Now find the example of Comparator.comparing method.
ComparingDemo.java
package com.concretepage;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ComparingDemo {
  public static void main(String[] args) {
    List<Student> list = Student.getStudentList();
    
    Comparator<Student> schoolComparator1 = Comparator.comparing(Student::getSchool);
    Collections.sort(list, schoolComparator1);
    list.forEach(s->System.out.print(s.getName() + "-" + s.getSchool().getSname() + " | "));
    System.out.println("\n-------------------");    
    
    Comparator<Student> schoolComparator2 = 
    	Comparator.comparing(Student::getSchool, (sch1, sch2) -> sch1.getCode() - sch2.getCode());
    Collections.sort(list, schoolComparator2);
    list.forEach(s->System.out.print(s.getName() + "-" + s.getSchool().getCode() + " | "));
    System.out.println("\n-------------------");    
    
    Comparator<Student> nameComparator1 = Comparator.comparing(Student::getName); 
    Collections.sort(list, nameComparator1);
    list.forEach(s->System.out.print(s.getName() + " "));
    System.out.println("\n-------------------");

    Comparator<Student> nameComparator2 = Comparator.comparing(Student::getName, (s1, s2) -> s2.compareTo(s1));     
    Collections.sort(list, nameComparator2);
    list.forEach(s->System.out.print(s.getName() + " "));    
  }
} 
Output
Shyam-RS College | Ram-PQ College | Mahesh-CD College | Mohan-AB College | 
-------------------
Ram-101 | Mohan-102 | Shyam-103 | Mahesh-104 | 
-------------------
Mahesh Mohan Ram Shyam 
-------------------
Shyam Ram Mohan Mahesh 
In the above example we are sorting collection using Collections.sort. We can also use Stream.sorted, List.sort and Arrays.sort to sort collections using comparator.

Comparator.comparingInt

Find the declaration of comparingInt method.
static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) 
It accepts a function that extracts an int sort key from a type T, and returns a Comparator that compares by that sort key. Find the example.
ComparingIntDemo.java
package com.concretepage;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ComparingIntDemo {
  public static void main(String[] args) {
    List<Student> list = Student.getStudentList();
    
    Collections.sort(list, Comparator.comparingInt(Student::getAge));
    list.forEach(s->System.out.print(s.getAge() + " "));    
  }
} 
Output
18 19 20 22 

Comparator.comparingLong

Find the declaration of comparingLong method.
static <T> Comparator<T> comparingLong(ToLongFunction<? super T> keyExtractor) 
It accepts a function that extracts a long sort key from a type T, and returns a Comparator that compares by that sort key. Find the example.
ComparingLongDemo.java
package com.concretepage;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ComparingLongDemo {
  public static void main(String[] args) {
    List<Student> list = Student.getStudentList();
    
    Collections.sort(list, Comparator.comparingLong(Student::getHomeDistance));
    list.forEach(s->System.out.print(s.getHomeDistance() + " "));           
  }
} 
Output
1459 3252 3455 4450 

Comparator.comparingDouble

Find the declaration of comparingDouble method.
static <T> Comparator<T> comparingDouble(ToDoubleFunction<? super T> keyExtractor) 
It accepts a function that extracts a double sort key from a type T, and returns a Comparator that compares by that sort key. Find the example.
ComparingDoubleDemo.java
package com.concretepage;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ComparingDoubleDemo {
  public static void main(String[] args) {
    List<Student> list = Student.getStudentList();
    
    Collections.sort(list, Comparator.comparingDouble(Student::getWeight));
    list.forEach(s->System.out.print(s.getWeight() + " "));           
  }
}
Output
60.75 65.2 65.8 70.25 

Reference

Interface Comparator
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us