1.sorted排序(升序)
List<String> list = Arrays.asList("aa", "ff", "dd","cc");
//String 类自身已实现Compareable接口
list.stream().sorted().forEach(System.out::println);
2.先按姓名升序,姓名相同则按年龄升序
Student s1 = new Student("aa", 10);
Student s2 = new Student("bb", 20);
Student s3 = new Student("aa", 30);
Student s4 = new Student("dd", 40);
List<Student> studentList = Arrays.asList(s1, s2, s3, s4);
studentList.stream().sorted(Comparator.comparing(Student::getName).reversed()).collect(Collectors.toList());
// 自定义排序:先按姓名升序,姓名相同则按年龄升序
studentList.stream().sorted(
(o1, o2) -> {
if (o1.getName().equals(o2.getName())) {
return o1.getAge() - o2.getAge();
} else {
return o1.getName().compareTo(o2.getName());
}
}
).forEach(System.out::println);
3.把年龄封装成List
List<Integer> ageList = studentList.stream().map(Student::getAge).collect(Collectors.toList());
4.获取最大年龄,获取最小年龄用min()
Integer max = studentList.stream().map(Student::getAge).max(Integer::compare).get();
5.获取平均年龄
Double aver = studentList.stream().collect(Collectors.averagingDouble(Student::getAge));
6.获取年龄和
Integer sum = studentList.stream().mapToInt(Student::getAge).sum();
7.Reduce合并流的元素,并生成一个值
int sum1 = Stream.of(1, 2, 3, 4).reduce(0, (a, b) -> a + b);