Home > Java > javaTutorial > What are the two ways to create anonymous objects in java

What are the two ways to create anonymous objects in java

王林
Release: 2023-05-02 21:43:10
forward
1270 people have browsed it

1. Static tool method

Collections.sort accepts a list and a Comparator interface as input parameters. The Comparator implementation class can compare elements in the input list. Normally, you can create an anonymous Comparator object directly and pass it as a parameter to the sort method.

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. Lambda expression

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

As you can see, this code is shorter and easier to read than the previous one. However, it can be even shorter:

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

Just one line of code, including the method body. You can even omit the braces {} and the return keyword. But this is not the shortest way of writing:

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

The Java compiler can automatically identify the type of parameters, so you can omit the type.

The above is the detailed content of What are the two ways to create anonymous objects 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