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

What are the two ways to create anonymous objects in java

王林
王林forward
2023-05-02 21:43:101225browse

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);
    }
});

2. Lambda expression

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

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));

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));

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete