Serializacja

import java.io.*;
 
class Student implements Serializable {
    private static final long serialVersionUID = 1L;
    String name;
    int grade;
    transient String password; // nie będzie serializowane
 
    Student(String name, int grade) { this.name = name; this.grade = grade; }
}
 
// Zapis (serializacja)
try (ObjectOutputStream oos = new ObjectOutputStream(
        new FileOutputStream("student.ser"))) {
    oos.writeObject(new Student("Ania", 5));
}
 
// Odczyt (deserializacja)
try (ObjectInputStream ois = new ObjectInputStream(
        new FileInputStream("student.ser"))) {
    Student s = (Student) ois.readObject();
    System.out.println(s.name + " - " + s.grade);
}

Przykłady praktyczne

Przetwarzanie listy studentów:

record Student(String name, int grade, String group) {}
 
List<Student> students = List.of(
    new Student("Ania",    5, "A"),
    new Student("Bartosz", 3, "B"),
    new Student("Ola",     4, "A"),
    new Student("Adam",    5, "B"),
    new Student("Beata",   3, "A")
);
 
// Najlepsi studenci z grupy A, posortowani alfabetycznie
List<String> topA = students.stream()
    .filter(s -> s.group().equals("A") && s.grade() >= 4)
    .sorted(Comparator.comparing(Student::name))
    .map(Student::name)
    .collect(Collectors.toList());
System.out.println(topA); // [Ania, Ola]
 
// Średnia ocena per grupa
Map<String, Double> avgByGroup = students.stream()
    .collect(Collectors.groupingBy(Student::group,
             Collectors.averagingInt(Student::grade)));
System.out.println(avgByGroup); // {A=4.0, B=4.0}
 
// Zapis do pliku
Path out = Path.of("students.txt");
Files.write(out, students.stream()
    .map(s -> s.name() + "," + s.grade() + "," + s.group())
    .collect(Collectors.toList()));