需求:
对象的list按照对象的某个属性进行排序
示例对象:
@Data
class txcClass{
private String name;
private int age;
public txcClass(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "txcClass{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
非stream写法:
// 初始化数据
List<txcClass> list = new ArrayList<>();
txcClass z3 = new txcClass("z3", 10);
txcClass l4 = new txcClass("l4", 20);
txcClass w5 = new txcClass("w5", 4);
list.add(z3);
list.add(l4);
list.add(w5);
//升序排列(降序把o1,o2调个位置)
Collections.sort(list, new Comparator<txcClass>() {
@Override
public int compare(txcClass o1, txcClass o2) {
return o1.getAge()-(o2.getAge());
}
});
stream写法:
//升序排列(降序把o1,o2调个位置)
List<txcClass> collect = list.stream().sorted((o1, o2) -> o1.getAge() - o2.getAge()).collect(Collectors.toList());
//上面同时等效于下面的写法(只有升序时等效,降序是不等效的)
List<txcClass> collect = list.stream().sorted(Comparator.comparingInt(txcClass::getAge)).collect(Collectors.toList());
collect.stream().forEach(b->{
System.out.println(b.toString());
});
降序排列的另一个写法
List<txcClass> collect = list.stream().sorted(Comparator.comparingInt(txcClass::getAge).reversed()).collect(Collectors.toList());
引申:
上述是对整个List进行排序,那如果我们只想按照txcClass的age排序,然后只返回name的集合,该如何操作呢?
此时使用stream操作更简便
List<String> collect = list.stream().sorted((o1, o2) -> o2.getAge() - o1.getAge())
.map(txcClass::getName)
.collect(Collectors.toList());
取前5条
List<txcClass> collect = list.stream().sorted(Comparator.comparingInt(txcClass::getAge).reversed()).limit(5).collect(Collectors.toList());