JSON 데이터를 읽고 분석한 후, 특정 요구 사항에 따라 학생들의 성적을 정리하고 Excel 파일로 출력하는 연습입니다.
요구 사항
- JSON 데이터를 읽습니다.
- 다음과 같이 학생 데이터를 분류 및 요약합니다.
- 20세 미만의 학생 수를 계산합니다.
- 여학생 중 국어 점수가 가장 높은 학생의 이름을 찾습니다.
- 남학생들의 수학 평균 점수를 두 자리까지 반올림하여 계산합니다.
- 영어 평균 점수가 가장 높은 선생님을 결정합니다.
- 학생들의 총점 순으로 정렬하여 최종 성적표를 Excel 파일로 저장합니다. 필수 항목: 학생 이름, 국어 점수, 수학 점수, 영어 점수, 총점.
파일
1. JSON 파일
파일명: students.jsonstudents.json 보기
[
{
"age": 19,
"korScore": 55,
"engScore": 31,
"gender": false,
"id": 1,
"mathScore": 75,
"name": "조양양",
"teacherName": "왕선생"
},
...
]
2. 엔티티 클래스
엔티티 이름: Student.javaStudent.java 보기
package com.example.practice;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private Long id;
private String name;
private int age;
private boolean gender;
private String teacherName;
private int mathScore;
private int korScore;
private int engScore;
}
코드 예제
package com.example.practice;
import com.alibaba.fastjson.JSONArray;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import java.util.OptionalDouble;
import java.util.stream.Collectors;
public class JsonHandler {
public static void main(String[] args) throws IOException {
Path path = Paths.get("src", "main", "resources", "students.json");
byte[] bytes = Files.readAllBytes(path);
String jsonString = new String(bytes);
JSONArray jsonArray = JSONArray.parseArray(jsonString);
List<Student> students = jsonArray.toJavaList(Student.class);
long underTwentyCount = students.stream().filter(s -> s.getAge() < 20).count();
System.out.println(underTwentyCount);
String topFemaleKor = students.stream()
.filter(s -> !s.isGender())
.max(Comparator.comparingInt(Student::getKorScore))
.map(Student::getName)
.orElse("");
System.out.println(topFemaleKor);
DecimalFormat df = new DecimalFormat("#.00");
OptionalDouble maleMathAvg = students.stream()
.filter(s -> s.isGender())
.mapToInt(Student::getMathScore)
.average();
System.out.println(df.format(maleMathAvg.orElse(0)));
Map avgEngScores = students.stream()
.collect(Collectors.groupingBy(Student::getTeacherName, Collectors.averagingDouble(Student::getEngScore)));
String bestTeacher = avgEngScores.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElse("");
System.out.println(bestTeacher);
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("이름");
headerRow.createCell(1).setCellValue("국어");
headerRow.createCell(2).setCellValue("수학");
headerRow.createCell(3).setCellValue("영어");
headerRow.createCell(4).setCellValue("총점");
students.stream()
.sorted((s1, s2) -> Integer.compare(
s2.getKorScore() + s2.getEngScore() + s2.getMathScore(),
s1.getKorScore() + s1.getEngScore() + s1.getMathScore()))
.forEach(student -> {
Row newRow = sheet.createRow(sheet.getLastRowNum() + 1);
newRow.createCell(0).setCellValue(student.getName());
newRow.createCell(1).setCellValue(student.getKorScore());
newRow.createCell(2).setCellValue(student.getMathScore());
newRow.createCell(3).setCellValue(student.getEngScore());
newRow.createCell(4).setCellValue(student.getKorScore() + student.getEngScore() + student.getMathScore());
});
Path outputPath = Paths.get("src", "main", "resources", "output.xlsx");
try (FileOutputStream fos = new FileOutputStream(outputPath.toFile())) {
workbook.write(fos);
}
}
}