一、基础数据的操作
/**
* 处理基础
*/
public static void basic(){
List<Integer> list = Arrays.asList(1,2,3,4,5,6,6,7,7,8,9,10);
//获取集合中大于5的元素
List<Integer> numGreaderFiveCollect = list.stream().distinct().filter(l -> l > 5).collect(Collectors.toList());
log.error("筛选集合中大于5的元素 :{}", numGreaderFiveCollect);
//过滤所有偶数
List<Integer> evenCollect = list.stream().filter(l -> l % 2 == 0).collect(Collectors.toList());
log.error("所有偶数 :{}", evenCollect);
//去重
List<Integer> distinctCollect = list.stream().distinct().collect(Collectors.toList());
log.error("去重后 :{}", distinctCollect);
//计算总和
//ifPresent如果不为null则执行
list.stream().reduce((a,b)-> a + b).ifPresent(s->log.error("总和:{}",s));
//正序排序
List<Integer> collect1 = list.stream().sorted().collect(Collectors.toList());
log.error("正序排序 :{}", collect1);
//倒叙排序
List<Integer> sorted = list.stream().sorted(Collections.reverseOrder()).collect(Collectors.toList());
log.error("倒叙排序 :{}", sorted);
//获取最大值
list.stream().max(Integer::compare).ifPresent(s->log.error("最大值:{}",s));
//获取最小值
list.stream().min(Integer::compare).ifPresent(s->log.error("最小值:{}",s));
}
二、对象类型数据
/**
* 处理对象
*/
public static void Object(){
List<Student> studentList = getStudentList();
//根据学生年龄升序排序
studentList.sort(Comparator.comparing(Student::getAge));
studentList.forEach(s -> log.error("根据学生年龄升序排序:{}", s));
//根据学生年龄降序排序
studentList.sort(Comparator.comparing(Student::getAge).reversed());
studentList.forEach(s -> log.error("根据学生年龄降序排序:{}", s));
//将所有学生名称生成一个新的集合
List<String> StudentNamecollect = studentList.stream().map(s -> s.getName()).collect(Collectors.toList());
log.error("所有学生名称:{}", StudentNamecollect);
}
/**
* 生成数据
*
* @return
*/
public static List<Student> getStudentList(){
List<Student> studentList = new ArrayList<>();
String[] names = {"张三","李四","王五"};
for(int i = 1; i < 4; i++){
Student student = new Student();
student.setName(names[i]);
student.setAge(new Random().nextInt(10));
studentList.add(student);
}
return studentList;
}