Lambda takes precedence over anonymous classes in java

Lambda expression is a new feature of java8. Using Lambda expression, we can use shorter code to complete the corresponding function

  • Suppose we need to sort the string list according to the length of the string. In fact, to sort the list, you can directly use the list.sort(Comparator) method, but there are many other implementation methods. The following is the sorting method using anonymous internal classes :
    public static void main(String[] args) {
    
    
        List<String> stringList=new LinkedList<>();
        stringList.add("hello");
        stringList.add("hell");
        stringList.add("hel");
        stringList.add("he");
        stringList.add("h");
        Collections.sort(stringList, new Comparator<String>() {
    
    
            @Override
            public int compare(String o1, String o2) {
    
    
                return Integer.compare(o1.length(), o2.length());
            }
        });
        System.out.println(stringList.toString());
    }

Use Lambda expressions for sorting, the code is as follows, (one point to note here is that there is no way to use this to represent its own object inside a method using lambda expressions):

    public static void main(String[] args) {
    
    
        List<String> stringList=new LinkedList<>();
        stringList.add("hello");
        stringList.add("hell");
        stringList.add("hel");
        stringList.add("he");
        stringList.add("h");
        Collections.sort(stringList, (o1, o2) -> Integer.compare(o1.length(), o2.length()));
        System.out.println(stringList.toString());
    }

The code can actually be more concise when using method references when we compare:

Collections.sort(stringList, Comparator.comparingInt(String::length));

But generally when we sort the list, we use the following method

list.sort(Comparator.comparingInt(String::length));

Guess you like

Origin blog.csdn.net/liu_12345_liu/article/details/102878002