jdk1.8中stream练习
public class stream {
public static void main(String[] args) {
List<Student> students = initData();
streamImpl(students);
java7Impl(students);
}
public static void streamImpl(List<Student> students){
Map<Double, Long> collect = students.stream().collect(groupingBy(Student::getScore, counting()));
for (Map.Entry<Double, Long> map :collect.entrySet()){
System.out.println("key:"+map.getKey()+"value:"+map.getValue());
}
List<Student>filterStudent = students.stream().filter(one -> one.getScore() < 60).collect(toList());
filterStudent.stream().forEach(System.out::println);
List<Student> collect1 = students.stream().filter(one -> one.getScore() < 60).collect(Collectors.toList());
collect1.stream().forEach(System.out::println);
List<Student> collect2 = students.stream().sorted(Comparator.comparing(Student::getScore)).collect(toList());
collect2.stream().forEach(System.out::println);
students.sort(Comparator.comparing(Student::getScore).thenComparing(Student::getId).reversed());
int sum = students.stream().mapToInt(scoreTo -> (int) scoreTo.getScore()).sum();
System.out.println(sum);
}
public static void java7Impl(List<Student> students) {
List<Student> filterStudent = new ArrayList<>();
for (Student student : students) {
if (student.getScore() < 60) {
filterStudent.add(student);
}
}
System.out.println(filterStudent);
}
public static List<Student> initData() {
List<Student> students = new ArrayList<>();
students.add(new Student("张三", 60));
students.add(new Student("李四", 80));
students.add(new Student("王五", 50));
students.add(new Student("赵六", 70));
students.add(new Student("孙七", 30));
students.add(new Student("周八", 30));
return students;
}
@Data
static class Student {
private String name;
private double score;
List<String> course;
public Student(int i, String 张三, int i1) {
}
public Student(String name, double score) {
this.name = name;
this.score = score;
}
}
}