Home  >  Article  >  Java  >  How to use Comparable and Comparator in Java

How to use Comparable and Comparator in Java

WBOY
WBOYforward
2023-05-03 10:07:061260browse

Comparable and Comparator

Comparable and Comparator are two Java sorting-related interfaces, also known as natural sorting and customized sorting. I have recently read relevant content, and now I will record my own learning status below.
Comparable and Comparator are two interfaces about sorting, used to implement the sorting function in Java collections. The specific functions can be obtained from the API.

Comparable

This is a brief introduction from the API documentation:

##This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method. Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

Usage:

Requires the implementation of Comparable for sorting entity classes interface and override the compareTo() method to have sorting functionality. Some collections (such as TreeSet) that automatically sort elements will automatically call the CompareTo() method for sorting when elements are put into the collection (provided that the elements must implement this interface). But it can also be used in other places, not just limited to TreeSet, it is widely used.

Comparator

This is a brief introduction from the API documentation:

##A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don’t have a natural ordering.

Usage:

Comparator is a third-party interface , the specific usage is: design a comparator, create a class, implement this interface, and override the compare() method. And since Comparator is a functional interface, Lambda expressions can be used instead of Comparator objects, making the code more concise and clear.

Talk is cheap, show me the code.

Note: The content in the blog may not be very detailed, so if you want to see the specific details, you should refer to books and official documents Mainly, the content here is more about briefly introducing the basic usage.

Test entity class: Dog

public class Dog implements Comparable<Dog>{
	private String name;
	private int age;
	
	public Dog(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	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;
	}
	
	@Override
	public String toString() {
		return "Dog [name=" + name + ", age=" + age + "]";
	}

	@Override
	public int compareTo(Dog dog) {
		return this.age > dog.age ? 1 : this.age < dog.age ? -1 : 0;
	}
}

Test entity class: Cat

public class Cat implements Comparable<Cat>{
	private String name;
	private Integer age;
	
	public Cat(String name, Integer age) {
		this.name = name;
		this.age = age;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "Cat [name=" + name + ", age=" + age + "]";
	}

	@Override
	public int compareTo(Cat o) {
		//可以直接调用,这样更简单
		//调换 o.age 和 this.age 就是相反的顺序
		return o.age.compareTo(this.age); 
	}
}

Test class :Test

public class Test {
	public static void main(String[] args) {
		List<Dog> dogs = new LinkedList<>();
		List<Cat> cats = new LinkedList<>();
		
		dogs.add(new Dog("大黄",6));
		dogs.add(new Dog("大白",1));
		dogs.add(new Dog("小黑",5));
		dogs.add(new Dog("旺财",3));
		dogs.add(new Dog("二哈",2));
		
		cats.add(new Cat("牛牛",3));
		cats.add(new Cat("花咪",4));
		cats.add(new Cat("咪咪",10));
		cats.add(new Cat("小黄",2));
		cats.add(new Cat("大橘",6));
		
		//参数为 null 使用 自然排序,否则使用 定制排序
		//也可以看出来 定制排序 优先级高于 自然排序
		System.out.println("---------自然排序 升序--------");
		dogs.sort(null);   
		dogs.forEach(System.out::println);
		System.out.println("---------自然排序 降序--------");
		cats.sort(null);
		cats.forEach(System.out::println);
		
		//定制排序
	    //Comparator<Dog> c = (e1,e2)->e2.getAge() - e1.getAge();
		//dogs.sort(c) 这个就是下面这个的具体形式,
		//可以看出来参数是一个 Comparator 对象  
		System.out.println("---------定制排序 降序--------");
		dogs.sort((e1,e2)->e2.getAge() - e1.getAge());
		//流式API的简单的应用,效果和上面的类似,或者直接使用 forEacn 循环遍历
		dogs.stream().forEach(System.out::println);
		System.out.println("---------定制排序 升序--------");
	//	另一种遍历方式,可以看出来函数式编程非常灵活,我也是初学,觉得很神奇。
		cats.stream()
		.sorted((e1,e2)->e1.getAge()-e2.getAge())
		.forEach(System.out::println);
	}
}

Running screenshot:

How to use Comparable and Comparator in Java

Supplementary instructions:

list.sort() MethodDescription in API documentation:

Sorts this list according to the order induced by the specified Comparator.
All elements in this list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the list). If the specified comparator is null then all elements in this list must implement the Comparable interface and the elements’s natural ordering should be used. This list must be modifiable, but need not be resizable.


As you can see, this method sorts through a Comparator object if the incoming parameter is null If so, natural sorting will be performed, but note: the premise of natural sorting is that the corresponding entity class implements the Comparable interface and overrides the compareTo() method.

The above is the detailed content of How to use Comparable and Comparator in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete