原文地址:https://www.cnblogs.com/xiaoxi/p/7099667.html
原文更详细,我只是记录一下自己的代码
public class Persion {
String name;
LocalDate localDate;
public Persion(String name,LocalDate localDate){
this.name = name;
this.localDate = localDate;
}
public static int compareByAge(Persion p ,Persion p1){
return p.localDate.compareTo(p1.localDate);
}
@Override
public String toString() {
return this.name;
}
}
public static void main(String[] args) {
Persion p1 = new Persion("小明", LocalDate.of(2018,6,6));
Persion p2 = new Persion("小红", LocalDate.of(2018,4,6));
Persion p3 = new Persion("小白", LocalDate.of(2018,6,22));
Persion [] p = new Persion[]{p1,p2,p3};
//不使用lambda表达式
Arrays.sort(p, new Comparator<Persion>() {
@Override
public int compare(Persion o1, Persion o2) {
return o1.localDate.compareTo(o2.localDate);
}
});
//使用Lambda表达式 不简化的方式
Arrays.sort(p,(Persion pp1, Persion pp2) -> {return pp1.localDate.compareTo(pp2.localDate);});
//使用Lambda表达式 简化的方式 (可以省略Persion)
Arrays.sort(p,(pp1,pp2) -> pp1.localDate.compareTo(pp2.localDate));
//使用Lambda表达式使用静态方法的引用 (其实是调用了Perion的compareByAge不需要传参数)
Arrays.sort(p,Persion::compareByAge);
System.out.println(Arrays.asList(p));
Map<Long,Double> roleServiceCountMap = new HashMap<>();
roleServiceCountMap.put(1000L,34.2);
roleServiceCountMap.put(2000L,120.34);
roleServiceCountMap.put(3000L,38.98);
List<Map.Entry<Long, Double>> list = new ArrayList<Map.Entry<Long,Double>>(roleServiceCountMap.entrySet());
Collections.sort(list,(o1, o2) -> BigDecimal.valueOf(o1.getValue()).compareTo(BigDecimal.valueOf(o2.getValue())));
list.forEach(item -> System.out.println(item.getKey()+"=="+item.getValue()));
}