欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Comparable和Comparator详解---java

程序员文章站 2022-05-23 14:16:48
...

Comparable和Comparator

java.lang.Comparable 传入一个对象与自己比较—>内比较器

接口中定义的方法:

public interface Comparable<T> {
    public int compareTo(T o);
}

Comparable来排序字符

import java.util.Collections;
import java.util.*;

public class ComparableTest01
{
	public static void main(String[] args){
		Person p1 = new Person("001","abc");
		Person p2 = new Person("002","bcd");
		Person p3 = new Person("003","aaa");
		List<Person> list = new ArrayList();
		List<Person> list1 = new LinkedList();

		list.add(p1);
		list.add(p2);
		list.add(p3);

		list1.add(p1);
		list1.add(p2);
		list1.add(p3);

		Collections.sort(list);
		Collections.sort(list1);

		System.out.println("ArrayList------->Comparable");
		list.forEach(System.out::println);
		System.out.println("LinkedList------->Comparable");
		list1.forEach(System.out::println);
		
	}
}

class Person implements Comparable<Person>
{
	String id;
	String name;
	
	public Person(String id,String name){
		this.id = id ;
		this.name = name;
	}
	public int compareTo(Person p ){
        //直接调用String的comparTo()方法
		return this.name.compareTo(p.name);
		
	}
	public String toString(){
		 return "Person{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                '}';
	}
}

Comparable比较数字

import java.util.*;
import java.util.Collections;

public class ComparableTest02
{
	public static void main(String[] args){
		Person p1 = new Person("abc",1);
		Person p2 = new Person("bcd",2);
		Person p3 = new Person("aaa",3);
		List<Person> list = new ArrayList();
		List<Person> list1 = new LinkedList();

		list.add(p1);
		list.add(p2);
		list.add(p3);

		list1.add(p1);
		list1.add(p2);
		list1.add(p3);

		Collections.sort(list);
		Collections.sort(list1);

		System.out.println("ArrayList------->Comparable");
		list.forEach(System.out::println);
		System.out.println("LinkedList------->Comparable");
		list1.forEach(System.out::println);
		
	}
}
//泛型必须写
class Person implements Comparable<Person>
{
	String name;
	int id;
	public Person(String name,int id){
		this.name = name ;
		this.id = id ;
	}
	public String toString(){
		return "Person{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                '}';
	}
	public int compareTo(Person p){
        //直接相减就行
		return this.id - p.id;
	}
}


运行结果:
Comparable和Comparator详解---java


java.util.Comparator 传入两个对象,进行比较—>外比较器

接口中的定义的方法:

public interface Comparator<T> {
	int compare(T o1, T o2);
	//省略其他方法...
}

下面用Comparator来比较字母

import java.text.Collator;
import java.util.*;

public class ComparatorTest
{
	public static void main(String[] args){
        Student t3 = new Student("003","小菜鸡");
		Student t1 = new Student("001","马云");
		Student t2 = new Student("002","马化腾");
		
		List<Student> list = new LinkedList();
		List<Student> list1 = new ArrayList();
		list.add(t1);
		list.add(t2);
		list.add(t3);
		
		list1.add(t1);
		list1.add(t2);
		list1.add(t3);

		Collections.sort(list,new SortId());
		Collections.sort(list1,new SortId());
		System.out.println("LinkedList---->根据id排序:");
		//Lambda表达式
		list.forEach(System.out::println);
		
		System.out.println("ArrayList---->根据id排序:");
		list1.forEach(System.out::println);
	}
}

class SortId implements Comparator<Student>{
	public int compare(Student t1 , Student t2){
		Comparator<Object> c = Collator.getInstance();
		return c.compare(t1.id,t2.id);
	}
	
}

class Student
{
	String id;
	String name;
	public Student(String id,String name){
		this.id = id;
		this.name = name;
	}
	public String toString(){
		return "Student{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                '}';
	}
}

运行结果:

Comparable和Comparator详解---java

下面用Comparator来比较数字

import java.text.Collator;
import java.util.*;

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

	Student t3 = new Student(3,"马云");
	Student t1 = new Student(1,"马云");
	Student t2 = new Student(2,"马化腾");
	
	List<Student> list = new LinkedList();
	List<Student> list1 = new ArrayList();
	
	list.add(t1);
	list.add(t2);
	list.add(t3);
	
	list1.add(t1);
	list1.add(t2);
	list1.add(t3);
	
	//采用匿名内部类
	Collections.sort(list,new Comparator<Student>(){
		public int compare(Student o1,Student o2){
			return o1.id-o2.id;
		}
	});
	//采用lambda表达式
	Collections.sort(list1,(o1,o2)->  o1.id-o2.id);
	System.out.println("LinkedList----->根据(int)类型的id排序");
	list.forEach(System.out::println);
	System.out.println("LinkedList----->根据(int)类型的id排序");
	list1.forEach(System.out::println);

	}
}

class Student
{
	int    id;
	String name;
	public Student(int id,String name){
		this.id = id;
		this.name = name;
	}
	public String toString(){
		return "Student{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                '}';
	}
}

下面用Comparator来比较汉字(汉字和字母不一样,但是java给程序员提供了方法,只是不是太准确…)

import java.text.Collator;
import java.util.*;

public class ComparatorTest03
{
	public static void main(String[] args){
			Student t3 = new Student(3,"安琪拉");
			Student t1 = new Student(1,"马云");
			Student t2 = new Student(2,"马化腾");
			
			List<Student> list = new LinkedList();
			List<Student> list1 = new ArrayList();
			
			list.add(t1);
			list.add(t2);
			list.add(t3);
			
			list1.add(t1);
			list1.add(t2);
			list1.add(t3);

			Collections.sort(list,new Comparator<Student>(){
				
				public int compare(Student o1,Student o2){
					Comparator<Object> c  = Collator.getInstance(Locale.CHINA);
					return c.compare(o1.name,o2.name);
				}
			});

//lambda表达式
			Collections.sort(list1,
				(o1,o2)->{
				
					Comparator<Object> c  = Collator.getInstance(Locale.CHINA);
				    return c.compare(o1.name,o2.name);

			            });

			System.out.println("LinkedList----->根据(int)类型的id排序");
			list.forEach(System.out::println);
			System.out.println("LinkedList----->根据(int)类型的id排序");
			list1.forEach(System.out::println);
	}
}

class Student
{
	int    id;
	String name;
	public Student(int id,String name){
		this.id = id;
		this.name = name;
	}
	public String toString(){
		return "Student{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                '}';
	}
}

运行结果:

Comparable和Comparator详解---java

下面来试试这个题:

使用Comparator排序
1.1 按学生年龄排序(升,降)
1.2 按学生性别排序(升,降)
1.3 按学生学号排序(升,降)
1.4 按学生姓名排序(升,降)
1.5 按学生年龄排序,年龄相同时再按性别排序,性别也相同时再按姓名排,姓名也相同时再按学号排


import java.text.Collator;
import java.util.*;

public class ComparatorTest04 {
    public static void main(String[] args) {
        Student student1 = new Student(23,"男","马云","123");
        Student student4 = new Student(24,"男","赵云","231");
        Student student7 = new Student(23,"男","安琪拉","223");
        Student student5 = new Student(27,"男","大小姐","132");
        Student student6 = new Student(23,"男","安琪拉","123");
        Student student2 = new Student(56,"女","貂蝉","123");
        Student student3 = new Student(23,"女","阿吊","322");

        List<Student> list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        list.add(student3);
        list.add(student4);
        list.add(student5);
        list.add(student6);
        list.add(student7);

        Collections.sort(list,
	(o1,o2)->{
	
	Comparator<Object> s = Collator.getInstance(Locale.CHINA);
		if(o1.age-o2.age==0){

		    if(s.compare(o1.sex,o2.sex)==0){
			if(s.compare(o1.name,o2.name)==0){
			    return s.compare(o1.id,o2.id);
			}
			return s.compare(o1.name,o2.name);
		    }
		    return s.compare(o1.sex,o2.sex);
		}
		return o1.age-o2.age;
	
	});
        list.forEach(System.out::println);
    }
}


class Student {
    int age ;
    String sex ;

    String name;
    String id;

    public Student(int age, String sex, String name, String id) {
        this.age = age;
        this.sex = sex;
        this.name = name;
        this.id = id;
    }

    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", sex='" + sex + '\'' +
                ", name='" + name + '\'' +
                ", id='" + id + '\'' +
                '}';
    }
}

运行结果:

Comparable和Comparator详解---java

Comparable接口和Comparator接口的区别

  • Comparable接口位于java.lang包下;Comparator则在java.util包下

  • 要实现Comparable接口,必须重写comparaTo()方法,主要偏向于传入一个值和自己比较,一般是内部使用;而实现Comparator接口可以在类外部使用,主要偏向于两个值比较。

  • Comparable接口中只有一个compareTo()方法;但是Comparator接口不仅提供了compara()方法,还提供了其他默认方法,如reversed()thenComparing(),使我们可以按照更多的方式进行排序。