Home > Java > javaTutorial > What are the methods for sorting collections in java

What are the methods for sorting collections in java

WBOY
Release: 2023-04-28 22:04:05
forward
2037 people have browsed it

1. The Collections tool class provides a static method sort method. The input parameter is a List collection. Compared with Comparator, the given List collection is sorted. The above example code creates an anonymous inner class to participate in. This kind of similar operation can be seen everywhere in our daily work.

List<String> names = Arrays.asList("peter", "anna", "mike", "xenia");
 
Collections.sort(names, new Comparator<String>() {
    @Override
    public int compare(String a, String b) {
        return b.compareTo(a);
    }
});
Copy after login

2. Use Lambda expressions

For code blocks that only contain one line of methods, we can omit the curly brackets and directly return the key code, which can be simpler.

Collections.sort(names, (String a, String b) -> b.compareTo(a));
Copy after login

What collection classes are there in Java?

Collections in Java are mainly divided into four categories:

1. List: ordered, repeatable;

2. Queue: ordered and repeatable;

3. Set: non-repeatable;

4. Map: unordered, with unique keys and non-unique values.

The above is the detailed content of What are the methods for sorting collections 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template