这个东西我目前目标就是看懂吧,我见识比较少,感觉这个用的地方还不是很多。
以一个自定义列表排序的例子作为记录吧。
首先匿名内部类一般是在你想用一个类作为参数并且它以后也没什么用了的时候,你嫌new它出来很麻烦,你就把它写到一起了。
List<Integer> ls= new ArrayList<Integer>();
Comparator<Integer> cp = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
};
Collections.sort(ls);
这时候的代码想干什么很明显,但是太长了,容易使人失去兴趣。
List<Integer> ls= new ArrayList<Integer>();
Collections.sort(ls, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
这时候就把那个其实是一次性的类给他永远留在调用它的小括号里了。
List<Integer> ls= new ArrayList<Integer>();
Collections.sort(ls, (o1, o2) -> o2 - o1);
可以看到代码变得非常的简洁。
原文:https://www.cnblogs.com/agnes6/p/13597718.html