42 lines
1.6 KiB
Java
42 lines
1.6 KiB
Java
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));
|
||
}
|
||
}
|