Table of Contents
Comparable and Comparator
Comparable
Home Java javaTutorial How to use Comparable and Comparator in Java

How to use Comparable and Comparator in Java

May 03, 2023 am 10:07 AM
java comparator comparable

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;
	}
}
Copy after login

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); 
	}
}
Copy after login

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);
	}
}
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

See all articles