List的sort()方法这样写对吗?

class M{
int age;
构造函数;
toString()方法;
}
main(){
List st=new ArrayList();
st.sort((o1,o2)->{M m1=(M)o1;M m2=(M)o2;//按照年龄降序排列
return m1.age>m2.age?-1:m1.age 另外,对于TreeSet以同样的lambda表达式定义排序规则:
class M{
int age;
构造函数;
toString()方法;
}
main(){
TreeSet st=new TreeSet((o1,o2)->{M m1=(M)o1;M m2=(M)o2;
return m1.age>m2.age?-1:m1.age<m2.age?1:0});
只要定义了排序规则,存入的元素就会以此规则自动排序,这个功能是哪段代码实现的?因为书上提到Comparator接口的int compare()方法,但是具体是什么联系呢?lambda表达式是重写了这个int compare()方法吗?

11
10
7
5
3
2

可以。

另外sort的lambda可以简化下:
st.sort((o1,o2)->((M)o2).age-((M)o1).age);

结果一样

https://ideone.com/iv6Fsb

在线通过测试。

第9行m1.age后缺少的代码为m2.age?-1:m1.age<m2.age?1:0});不知道为什么显示不出

TreeSet不需要sort,它内部就是排序的。确切地说,每次有元素被添加,它都会调整内部的排序二叉树,将元素放在合适的位置上,保持它始终有序。

 /* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;


class M{
public int age;
public M(int n) { age = n; }
public String toString() { return String.valueOf(age); }
}

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        List st=new ArrayList();
        st.add(new M(10));
        st.add(new M(5));
        st.add(new M(2));
        st.add(new M(7));
        st.add(new M(11));
        st.add(new M(3));
        st.sort((o1,o2)->{M m1=(M)o1;M m2=(M)o2;//按照年龄降序排列
        return m1.age>m2.age?-1:(m1.age<m2.age?1:0);});
        for (Object m: st)
        System.out.println((M)m);
    }
}

treeset的:

 /* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;


class M{
public int age;
public M(int n) { age = n; }
public String toString() { return String.valueOf(age); }
}

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        TreeSet st =new TreeSet((o1,o2)->((M)o2).age-((M)o1).age);
        st.add(new M(10));
        st.add(new M(5));
        st.add(new M(2));
        st.add(new M(7));
        st.add(new M(11));
        st.add(new M(3));
        for (Object m: st)
        System.out.println((M)m);
    }
}

结果一样

https://ideone.com/iv6Fsb

在线通过测试。