Home > Java > javaTutorial > How to Sort Java Collections: Comparator, Comparable, and Lambda Expressions?

How to Sort Java Collections: Comparator, Comparable, and Lambda Expressions?

Susan Sarandon
Release: 2024-11-07 22:49:02
Original
710 people have browsed it

How to Sort Java Collections: Comparator, Comparable, and Lambda Expressions?

Sorting Java Collections

To sort a Java Collection, there are several approaches to consider, depending on the specific requirements. One common option is to utilize a Comparator.

Using a Comparator:

Create a Comparator class that implements the Comparator interface. Within the compare() method, you define the logic for comparing objects. For example, to sort a CustomObject by its id field:

Comparator<CustomObject> comparator = new Comparator<CustomObject>() {
    @Override
    public int compare(CustomObject left, CustomObject right) {
        return left.getId() - right.getId();
    }
};
Copy after login

Then, use the Comparator to sort the collection using Collections.sort():

Collections.sort(list, comparator);
Copy after login

Alternatively, if your CustomObject implements Comparable, you can directly use Collections.sort(list).

With JDK 8 Lambda Expressions:

Introduced in JDK 8, lambda expressions provide a convenient way to write Comparators:

Collections.sort(list, (left, right) -> left.getId() - right.getId());
Copy after login

Shorthand Notation with JDK 8:

For simple scenarios, the following shorthand notation can be used to sort by a specific field:

list.sort(Comparator.comparing(CustomObject::getId));
Copy after login

Ultimately, the best approach for sorting a Java Collection depends on the specific needs and Java version being used.

The above is the detailed content of How to Sort Java Collections: Comparator, Comparable, and Lambda Expressions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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 Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template