Java8新特性之stream流的使用
1、新建一个实体类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student implements Serializable {
private static final long serialVersionUID = -6936991705437335757L;
private Integer id;
private String name;
private Integer age;
private String grade;
private Integer weight;
}
2、stream流应用案列
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.*;
import java.util.stream.Collectors;
@Controller
@RequestMapping("test")
public class StudentController {
@PostMapping("test")
public void test() {
List<Student> students = Arrays.asList(
new Student(5, "小高", 15, "98",60),
new Student(1, "小高", 17, "98",60),
new Student(3, "小张", 20, "50",40),
new Student(4, "小胡", 23, "98",30),
new Student(2, "小叶", 22, "98",50)
);
List<Student> student1 = students.stream().filter(x -> x.getAge() > 18)
.collect(Collectors.toList());
System.out.println(student1);
List<Integer> id1 = student1.stream().map(Student::getId).collect(Collectors.toList());
System.out.println(id1);
List<Integer> id2 = students.stream().filter(x -> x.getAge() > 18).map(Student::getId)
.collect(Collectors.toList());
System.out.println(id2);
Map<String, List<Student>> student2 = students.stream().collect(Collectors.groupingBy(Student::getName));
System.out.println(student2);
Map<String, Long> studentNum = students.stream().collect(Collectors.groupingBy(Student::getName
, Collectors.counting()));
System.out.println(studentNum);
Map<String, Map<Integer, List<Student>>> student3 = students.stream().collect(Collectors.groupingBy(Student::getName,
Collectors.groupingBy(Student::getAge)));
System.out.println(student3);
List<Student> userRoles = students.stream().collect(
Collectors.collectingAndThen(Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(o -> o.getName()
+ o.getAge()))), ArrayList::new));
System.out.println(userRoles);
List<Student> students4 = students.stream().distinct().collect(Collectors.toList());
System.out.println(students4);
Map<String, List<Student>> map = new HashMap<>();
student2.entrySet().stream().sorted(Map.Entry.<String, List<Student>>comparingByKey()
.reversed()) .forEachOrdered(x -> map.put(x.getKey(), x.getValue()));
System.out.println(map);
students.forEach(y -> {
Map<String, Object> result = new HashMap<>();
});
List<Student> students5 = students.stream().sorted(Comparator.comparing(Student::getWeight)).collect(Collectors.toList());
System.out.println(students5);
List<Student> students6 = students.stream().sorted(Comparator.comparing(Student::getWeight).reversed()).collect(Collectors.toList());
System.out.println(students6);
}
}