Home> Java> javaTutorial> body text

How to use Comparator in java

WBOY
Release: 2023-05-10 18:31:15
forward
2233 people have browsed it

1. Description

Java provides the comparison interface Comparable for comparison. All classes that implement this interface dynamically implement this comparison method. In fact, Java not only provides a comparison interface, but also provides another interface. The Comparator interface also has a comparison function, but this interface focuses on comparing containers.

2. Example

Comparator was widely used before Java8. Java8 not only upgrades to functional interfaces, but also extends default methods.

Comparator comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName); Person p1 = new Person("John", "Doe"); Person p2 = new Person("Alice", "Wonderland"); comparator.compare(p1, p2); // > 0 comparator.reversed().compare(p1, p2); // < 0
Copy after login

What is Java

Java is an object-oriented programming language that can write desktop applications, Web applications, distributed systems and embedded system applications.

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

Related labels:
source:yisu.com
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!