使用Java8 新特性 stream 流 sorted 方法进行排序
package com.fdas.finance2.modular;
import cn.hutool.core.util.RandomUtil;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* 使用Java8 新特性 stream 流 sorted 方法进行排序
*/
public class StreamSort {
@Data
public static class Person{
private String name;
private Integer age;
private Integer income;
}
public static void main(String[] args) {
List<Person> list = new ArrayList<>();
for(int i = 0; i < 10; i++){
Person person = new Person();
person.setAge(RandomUtil.randomInt(5));
person.setIncome(RandomUtil.randomInt(5)*100);
person.setName("张三" + RandomUtil.randomInt(5));
list.add(person);
}
// 按照年龄 和 收入 进行倒序排序
// list.stream().forEach(System.out::println);
List<Person> collect = list.stream().sorted((a, b) -> {
if (a.getAge() == b.getAge()) {
if(a.getIncome() == b.getIncome()) {
return 0;
}else if(a.getIncome() > b.getIncome()) {
return -1;
}else if(a.getIncome() < b.getIncome()) {
return 1;
}
} else if (a.getAge() > b.getAge()) {
return -1;
} if (a.getAge() < b.getAge()) {
return 1;
}
return 0;
}).collect(Collectors.toList());
collect.stream().forEach(System.out::println);
/**
StreamSort.Person(name=张三3, age=4, income=400)
StreamSort.Person(name=张三2, age=4, income=300)
StreamSort.Person(name=张三2, age=4, income=100)
StreamSort.Person(name=张三3, age=3, income=300)
StreamSort.Person(name=张三4, age=3, income=200)
StreamSort.Person(name=张三3, age=3, income=200)
StreamSort.Person(name=张三0, age=0, income=400)
StreamSort.Person(name=张三4, age=0, income=200)
StreamSort.Person(name=张三1, age=0, income=0)
StreamSort.Person(name=张三0, age=0, income=0)
*/
/**
通过以上运行结果可以看出,
倒序(大的在前面): a > b 返回 -1,a < b 返回 1
升序(小的在前面): a > b 返回 1,a < b 返回 -1
*/
}
}
最后修改于 2022-01-14 19:01:07
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付

