个性化阅读
专注于IT技术分析

Java Comparator接口

点击下载

本文概述

Java Comparator接口用于对用户定义的类的对象进行排序。

该接口在java.util包中找到, 包含2个方法compare(Object obj1, Object obj2)和equals(Object element)。

它提供了多种排序顺序, 即你可以根据任何数据成员对元素进行排序, 例如rollno, 名称, 年龄或其他任何内容。

Java比较器接口的方法

方法 描述
public int compare(Object obj1, Object obj2) 它将第一个对象与第二个对象进行比较。
public boolean equals(Object obj) 用于将当前对象与指定对象进行比较。
public boolean equals(Object obj) 用于将当前对象与指定对象进行比较。

收藏类

Collections类提供用于对集合的元素进行排序的静态方法。如果集合元素是Set或Map, 则可以使用TreeSet或TreeMap。但是, 我们无法对List的元素进行排序。 Collections类还提供用于对List类型元素的元素进行排序的方法。

用于对List元素进行排序的Collections类的方法

public void sort(List list, Comparator c):用于按给定的Comparator对List的元素进行排序。


Java比较器示例(非通用旧样式)

让我们来看一个根据年龄和姓名对List元素进行排序的示例。在此示例中, 我们创建了4个Java类:

  1. Student.java
  2. AgeComparator.java
  3. NameComparator.java
  4. Simple.java

Student.java

此类包含三个字段rollno, name和age和一个参数化的构造函数。

class Student{
int rollno;
String name;
int age;
Student(int rollno, String name, int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}

AgeComparator.java

此类基于年龄定义比较逻辑。如果第一个对象的年龄大于第二个对象的年龄, 则我们将返回一个正值。可以是1、2、10之类的任何值。如果第一个对象的年龄小于第二个对象, 我们将返回一个负值, 它可以是任何负值, 并且如果两个对象的年龄相等, 我们返回0。

import java.util.*;
class AgeComparator implements Comparator{
public int compare(Object o1, Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;

if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
}
}

NameComparator.java

此类提供基于名称的比较逻辑。在这种情况下, 我们使用String类的compareTo()方法, 该方法在内部提供比较逻辑。

import java.util.*;
class NameComparator implements Comparator{
public int compare(Object o1, Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;

return s1.name.compareTo(s2.name);
}
}

Simple.java

在此类中, 我们将根据名称和年龄进行排序, 以打印对象的值。

import java.util.*;
import java.io.*;

class Simple{
public static void main(String args[]){

ArrayList al=new ArrayList();
al.add(new Student(101, "Vijay", 23));
al.add(new Student(106, "Ajay", 27));
al.add(new Student(105, "Jai", 21));

System.out.println("Sorting by Name");

Collections.sort(al, new NameComparator());
Iterator itr=al.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}

System.out.println("Sorting by age");

Collections.sort(al, new AgeComparator());
Iterator itr2=al.iterator();
while(itr2.hasNext()){
Student st=(Student)itr2.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}


}
}
Sorting by Name
       106 Ajay 27
       105 Jai 21
       101 Vijay 23
       
       Sorting by age       
       105 Jai 21
       101 Vijay 23
       106 Ajay 27

Java比较器示例(通用)

Student.java

class Student{
int rollno;
String name;
int age;
Student(int rollno, String name, int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}

AgeComparator.java

import java.util.*;
class AgeComparator implements Comparator<Student>{
public int compare(Student s1, Student s2){
if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
}
}

NameComparator.java

此类提供基于名称的比较逻辑。在这种情况下, 我们使用String类的compareTo()方法, 该方法在内部提供比较逻辑。

import java.util.*;
class NameComparator implements Comparator<Student>{
public int compare(Student s1, Student s2){
return s1.name.compareTo(s2.name);
}
}

Simple.java

在此类中, 我们将根据名称和年龄进行排序, 以打印对象的值。

import java.util.*;
import java.io.*;
class Simple{
public static void main(String args[]){

ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101, "Vijay", 23));
al.add(new Student(106, "Ajay", 27));
al.add(new Student(105, "Jai", 21));

System.out.println("Sorting by Name");

Collections.sort(al, new NameComparator());
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}

System.out.println("Sorting by age");

Collections.sort(al, new AgeComparator());
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Sorting by Name
       106 Ajay 27
       105 Jai 21
       101 Vijay 23

       Sorting by age     
       105 Jai 21
       101 Vijay 23
       106 Ajay 27

Java 8比较器界面

Java 8 Comparator接口是仅包含一种抽象方法的功能接口。现在, 我们可以将Comparator接口用作lambda表达式或方法引用的分配目标。

Java 8比较器接口的方法

方法 描述
int compare(T o1, T o2) 它将第一个对象与第二个对象进行比较。
静态<T, U扩展了Comparable <?超级U >>比较器<T>比较(功能<?超级T , ?扩展U> keyExtractor) 它接受一个函数, 该函数从类型T中提取一个Comparable排序键, 然后返回一个与该排序键进行比较的Comparator。
静态<T, U> Comparator <T>比较(Function <?super T, ?extended U> keyExtractor, Comparator <?super U> keyComparator) 它接受一个函数, 该函数从类型T中提取一个排序键, 然后返回一个比较器, 该比较器使用指定的比较器通过该排序键进行比较。
静态<T>比较器<T> compareDouble(ToDoubleFunction <?super T> keyExtractor) 它接受一个函数, 该函数从类型T中提取一个双精度排序键, 然后返回一个与该排序键进行比较的Comparator。
静态<T>比较器<T> compareInt(ToIntFunction <?super T> keyExtractor) 它接受一个函数, 该函数从类型T中提取一个int排序键, 然后返回一个与该排序键进行比较的Comparator。
静态<T>比较器<T> compareingLong(ToLongFunction <?super T> keyExtractor) 它接受一个函数, 该函数从类型T中提取一个长排序键, 然后返回一个与该排序键进行比较的Comparator。
boolean equals(Object obj) 用于将当前对象与指定对象进行比较。
静态<T扩展Comparable <?超级T >>比较器<T> naturalOrder() 它返回一个比较器, 该比较器以自然顺序比较可比较对象。
静态<T> Comparator <T> nullsFirst(Comparator <?super T>比较器) 它返回一个比较器, 该比较器将null小于非null元素。
静态<T> Comparator <T> nullsLast(Comparator <?super T>比较器) 它返回一个比较器, 该比较器将null大于非null元素。
默认Comparator <T> reversed() 它返回包含所提供比较器的反向顺序的比较器。
静态<T扩展Comparable <?超级T >> Comparator <T> reverseOrder() 它返回包含自然顺序相反的比较器。
默认的Comparator <T> thenComparing(Comparator <?super T>其他) 它返回一个字典顺序比较器和另一个比较器。
默认<U扩展Comparable <? super U >> Comparator <T> thenComparing(Function <?super T, ?extended U> keyExtractor) 它返回具有按可比排序键提取功能的字典顺序比较器。
默认<U> Comparator <T> thenComparing(Function <?super T, ?extended U> keyExtractor, Comparator <?super U> keyComparator) 它返回字典顺序比较器, 该函数具有提取要与给定Comparator比较的键的功能。
默认Comparator <T> thenComparingDouble(ToDoubleFunction <?super T> keyExtractor) 它返回一个字典顺序比较器, 该函数具有提取双精度排序键的函数。
默认Comparator <T> thenComparingInt(ToIntFunction <?super T> keyExtractor) 它返回字典顺序比较器, 该函数具有提取int排序键的函数。
默认Comparator <T> thenComparingLong(ToLongFunction <?super T> keyExtractor) 它返回一个字典顺序比较器, 该函数具有提取长排序键的功能。

Java 8比较器示例

让我们来看一个根据年龄和姓名对List元素进行排序的示例。

档案:Student.java

class Student {  
   int rollno;  
   String name;  
  int age;  
    Student(int rollno, String name, int age){  
    this.rollno=rollno;  
    this.name=name;  
    this.age=age;  
    }

	public int getRollno() {
		return rollno;
	}

	public void setRollno(int rollno) {
		this.rollno = rollno;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

    }

文件:TestSort1.java

import java.util.*;  
    public class TestSort1{  
    public static void main(String args[]){  
    ArrayList<Student> al=new ArrayList<Student>();  
    al.add(new Student(101, "Vijay", 23));  
    al.add(new Student(106, "Ajay", 27));  
    al.add(new Student(105, "Jai", 21)); 
	//Sorting elements on the basis of name
    Comparator<Student> cm1=Comparator.comparing(Student::getName);
     Collections.sort(al, cm1);
     System.out.println("Sorting by Name");
     for(Student st: al){
    	 System.out.println(st.rollno+" "+st.name+" "+st.age);
    	 }
     //Sorting elements on the basis of age
      Comparator<Student> cm2=Comparator.comparing(Student::getAge);
	 Collections.sort(al, cm2);
     System.out.println("Sorting by Age");
     for(Student st: al){
    	 System.out.println(st.rollno+" "+st.name+" "+st.age);
    	 }  
    }  
    }
Sorting by Name
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by Age
105 Jai 21
101 Vijay 23
106 Ajay 27

Java 8 Comparator示例:nullsFirst()和nullsLast()方法

在这里, 我们对也包含null的元素列表进行排序。

档案:Student.java

class Student {  
   int rollno;  
   String name;  
  int age;  
    Student(int rollno, String name, int age){  
    this.rollno=rollno;  
    this.name=name;  
    this.age=age;  
    }
	public int getRollno() {
		return rollno;
	}
	public void setRollno(int rollno) {
		this.rollno = rollno;
	}
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
    }

文件:TestSort2.java

import java.util.*;  
    public class TestSort2{  
    public static void main(String args[]){  
    ArrayList<Student> al=new ArrayList<Student>();  
    al.add(new Student(101, "Vijay", 23));  
    al.add(new Student(106, "Ajay", 27));  
    al.add(new Student(105, null, 21));  
    Comparator<Student> cm1=Comparator.comparing(Student::getName, Comparator.nullsFirst(String::compareTo));
     Collections.sort(al, cm1);
     System.out.println("Considers null to be less than non-null");
     for(Student st: al){
    	 System.out.println(st.rollno+" "+st.name+" "+st.age);
    	 }
     Comparator<Student> cm2=Comparator.comparing(Student::getName, Comparator.nullsLast(String::compareTo));
     Collections.sort(al, cm2);
     System.out.println("Considers null to be greater than non-null");
     for(Student st: al){
    	 System.out.println(st.rollno+" "+st.name+" "+st.age);
    	 }
    }  
    }
Considers null to be less than non-null
105 null 21
106 Ajay 27
101 Vijay 23
Considers null to be greater than non-null
106 Ajay 27
101 Vijay 23
105 null 21
赞(0)
未经允许不得转载:srcmini » Java Comparator接口

评论 抢沙发

评论前必须登录!