rika19/src/main/java/com/example/StudentApplication.java

42 lines
1.6 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.example;
import com.example.domain.Student;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StudentApplication {
public static void main(String[] args) {
// 设置编码(仅在需要时启用)
try {
System.setOut(new java.io.PrintStream(System.out,true,"UTF-8"));
} catch (java.io.UnsupportedEncodingException e) {
System.err.println("无法设置UTF-8编码" + e.getMessage());
}
// 创建一个学生集合包含5个学生信息。
List<Student> students = new ArrayList<>();
// 添加学生信息
students.add(new Student(1,"张三","语文",100));
students.add(new Student(2,"张三","数学",90));
students.add(new Student(3,"李四","英语",80));
students.add(new Student(4,"李四","物理",85));
students.add(new Student(5,"王五","化学",95));
// 使用Stream API将学生信息转换为字符串集合
List<String> studentStrings = students.stream()
.map(Student::toString)
.collect(Collectors.toList());
// 打印拼接后的字符串集合
System.out.println("学生信息集合:");
studentStrings.forEach(System.out::println);
//使用stream操作集合并输出每个人的名字及其平均成绩
students.stream()
.collect(Collectors.groupingBy(Student::getName, Collectors.averagingDouble(Student::getScore)))
.forEach((name, averageScore) -> System.out.println("姓名:" + name + ",平均成绩:" + averageScore));
}
}