Introduction and difference examples of Comparator and Comparable in java
This article first introduces the two interfaces Comparable and Comparator and their differences; then, uses examples to explain their use.
Comparable Introduction
Comparable is a sorting interface.
If a class implements the Comparable interface, it means "this class supports sorting". Since the class that implements the Comparable interface supports sorting, assuming that there is now a "List (or array) of objects of the class that implements the Comparable interface", the List (or array) can be processed through Collections.sort (or Arrays.sort) Sort.
In addition, "objects of classes that implement the Comparable interface" can be used as keys in "ordered maps (such as TreeMap)" or elements in "ordered sets (TreeSet)" without specifying comparisons. device.
1. The code of Comparable is as follows:
public interface Comparable<T> {public int compareTo(T o); }
2. The code of Comparator is as follows
public interface Comparator<T> {int compare(T o1, T o2);boolean equals(Object obj); // jdk1.8 后的方法default Comparator<T> reversed() {return Collections.reverseOrder(this); }default Comparator<T> thenComparing(Comparator<? super T> other) { Objects.requireNonNull(other);return (Comparator<T> & Serializable) (c1, c2) -> {int res = compare(c1, c2);return (res != 0) ? res : other.compare(c1, c2); }; }default <U> Comparator<T> thenComparing( Function<? super T, ? extends U> keyExtractor, Comparator<? super U> keyComparator) {return thenComparing(comparing(keyExtractor, keyComparator)); }default <U extends Comparable<? super U>> Comparator<T> thenComparing( Function<? super T, ? extends U> keyExtractor) {return thenComparing(comparing(keyExtractor)); }default Comparator<T> thenComparingInt(ToIntFunction<? super T> keyExtractor) {return thenComparing(comparingInt(keyExtractor)); }default Comparator<T> thenComparingLong(ToLongFunction<? super T> keyExtractor) {return thenComparing(comparingLong(keyExtractor)); }default Comparator<T> thenComparingDouble(ToDoubleFunction<? super T> keyExtractor) {return thenComparing(comparingDouble(keyExtractor)); }public static <T extends Comparable<? super T>> Comparator<T> reverseOrder() {return Collections.reverseOrder(); } @SuppressWarnings("unchecked")public static <T extends Comparable<? super T>> Comparator<T> naturalOrder() {return (Comparator<T>) Comparators.NaturalOrderComparator.INSTANCE; }public static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator) {return new Comparators.NullComparator<>(true, comparator); }public static <T> Comparator<T> nullsLast(Comparator<? super T> comparator) {return new Comparators.NullComparator<>(false, comparator); }public static <T, U> Comparator<T> comparing( Function<? super T, ? extends U> keyExtractor, Comparator<? super U> keyComparator) { Objects.requireNonNull(keyExtractor); Objects.requireNonNull(keyComparator);return (Comparator<T> & Serializable) (c1, c2) -> keyComparator.compare(keyExtractor.apply(c1), keyExtractor.apply(c2)); }public static <T, U extends Comparable<? super U>> Comparator<T> comparing( Function<? super T, ? extends U> keyExtractor) { Objects.requireNonNull(keyExtractor);return (Comparator<T> & Serializable) (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2)); }public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) { Objects.requireNonNull(keyExtractor);return (Comparator<T> & Serializable) (c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2)); }public static <T> Comparator<T> comparingLong(ToLongFunction<? super T> keyExtractor) { Objects.requireNonNull(keyExtractor);return (Comparator<T> & Serializable) (c1, c2) -> Long.compare(keyExtractor.applyAsLong(c1), keyExtractor.applyAsLong(c2)); }public static<T> Comparator<T> comparingDouble(ToDoubleFunction<? super T> keyExtractor) { Objects.requireNonNull(keyExtractor);return (Comparator<T> & Serializable) (c1, c2) -> Double.compare(keyExtractor.applyAsDouble(c1), keyExtractor.applyAsDouble(c2)); } }
The main features of Comparable and Comparator The difference is:
(1).Comparator and Comparable are both internal comparator interfaces in Java, and are used to sort a custom class
(2). The difference is that the implementation of the Comparable interface is defined inside the class, and the comparison code needs to be embedded in the internal structure of the class
(3 ). Comparator is implemented outside the class, and the first comparator is implemented separately. There is no need to make structural changes to the original class, and it is non-intrusive.
For example, implement the Comparable interface:
class Score implements Comparable<Score>{ public int score; public int time; public int getScore() { return score; } public void setScore(int score) { this.score = score; } public int getTime() { return time; } public void setTime(int time) { this.time = time; } @Override public int compareTo(Score o) { if(this.time>o.time) return 1; else if(this.time==o.time) return 0; else return -1; } public Score(int score, int time) { super(); this.score = score; this.time = time; } }
Example of implementing the Comparator interface:
class ScoreComparator implements Comparator<Score>{ @Override public int compare(Score o1, Score o2) { if(o1.time>o2.time) return 1; else if(o1.time==o2.time) return 0; else return -1; } }
Then call ScoreComparator:
Arrays.sort(score, new ScoreComparator());
The above is the detailed content of Introduction and difference examples of Comparator and Comparable in java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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

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

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

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
