java8 - sort 方法
作者:互联网
java8 中 使用sort 排序的列子。
基础类
@Data
@ToString
public class Persion {
private String name;
private Integer age;
public Persion(String name, Integer age) {
this.name = name;
this.age = age;
}
}
初始化 list
List<Persion> persions = Lists.newArrayList ();
persions.add (new Persion ("lucy",12));
persions.add (new Persion ("river",20));
persions.add (new Persion ("frank",5));
lis t中的数据 按照 persion 的年龄 升序排列
persions.sort(Comparator.comparing(Persion::getAge));
System.out.println(persions);
输出结果
[Persion(name=frank, age=5), Persion(name=lucy, age=12), Persion(name=river, age=20)]
按照 persion 的年龄降序排列
persions.sort(Comparator.comparing(Persion::getAge).reversed());
System.out.println(persions);
输出结果
[Persion(name=river, age=20), Persion(name=lucy, age=12), Persion(name=frank, age=5)]
可以自己写排序的策略
persions.sort((t1,t2)->{
if(t1.getAge() > t2.getAge()){
return -1;
}
return 1;
});
输出结果
[Persion(name=river, age=20), Persion(name=lucy, age=12), Persion(name=frank, age=5)]
标签:sort,persions,20,name,age,Persion,方法,java8 来源: https://www.cnblogs.com/ljyniki/p/11283634.html