public class Apple{
String color;
Integer size;
Float weight;
public Apple() {
}
public Apple(String color, Integer size, Float weight) {
this.color = color;
this.size = size;
this.weight = weight;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Integer getSize() {
return size;
}
public void setSize(Integer size) {
this.size = size;
}
public Float getWeight() {
return weight;
}
public void setWeight(Float weight) {
this.weight = weight;
}
@Override
public String toString() {
return "Apple{" +
"weight=" + weight +
", size=" + size +
", color=" + color +
'}';
}
}
主函数 一个赋值一个打印
public static void main(String[] args) {
List<Apple> appleList = new ArrayList<>();
appleList.add(new Apple("red",111,333F));
appleList.add(new Apple("yellow",333,222F));
appleList.add(new Apple("blue",222,888F));
appleList.add(new Apple("black",555,777F));
appleList.add(new Apple("pink",444,111F));
appleList.add(new Apple("green",666,444F));
}
private static <T> void forEach(List<T> list){
for(Object vo : list){
System.out.println(vo.toString());
}
}
第一级:传递代码
Apple类实现Comparator 复写compare
public class Apple implements Comparator<Apple> {
String color;
Integer size;
Float weight;
@Override
public int compare(Apple o1, Apple o2) {
return o1.getSize().compareTo(o2.getSize());
}
……
}
appleList.sort(new Apple());
forEach(appleList);
打印结果:
第二级:匿名类
Apple类还原 不用实现Comparator
appleList.sort(new Comparator<Apple>() {
@Override
public int compare(Apple o1, Apple o2) {
return o1.getSize().compareTo(o2.getSize());
}
});
forEach(appleList);
打印结果一样
第三级:使用Lambda表达式
一样的传递代码 轻量的写法
appleList.sort((Apple o1,Apple o2) -> o1.getSize().compareTo(o2.getSize()));
forEach(appleList);
能再简洁点吗? 能。
Java编译器可以根据lambda的上下文来推断表达式参数的类型,所以写Lambda的时候可以省略参数类型
appleList.sort((o1,o2) -> o1.getSize().compareTo(o2.getSize()));
forEach(appleList);
还能再简洁点吗? 能。
Comparator有一个comparing的静态辅助方法,可以接受一个函数来提取Comparable的键值,并生成一个Comparator对象
appleList.sort(Comparator.comparing((a)->a.getSize()));
forEach(appleList);
第四级:使用方法引用
appleList.sort(Comparator.comparing(Apple::getSize));
forEach(appleList);
方法引用仅仅是涉及单一方法的Lampbda语法糖,使用方式和PHP中的调用静态方法一样,类::方法。
Linux公社的RSS地址:https://www.linuxidc.com/rssFeed.aspx