带if条件的双for循环

问题描述

我在java中使用double for循环遇到麻烦,特别是内部if条件

这是我的代码

 public Set<Term> getAllTermsForStudent(Long id) {

        List<Term> terms = termRepository.findAll();
        Set<Term> set_terms = new HashSet<Term>(terms); //there are 3 terms
        Set<Exam> exams = studentService.getStudentExams(id); //in this student's case,there are 9 exams,3 in each term
        Set<Exam> new_exams = new HashSet<>();

        for(Term t: set_terms) { 
            for(Exam e: exams) {
                if(t.getId() == e.getTerm().getId()) { //exam has term id,which indicates to which
                                                         term it belongs,so I'm comparing it,and I 
                                                         want to add it to new exam set
                    new_exams.add(e);
                }
            }
           t.setExams(new_exams);

        }

        return set_terms;
    }

功能输出每学期给我9次考试,就像忽略条件一样

解决方法

此功能的输出每学期给我9次考试,就像忽略条件一样

那是因为您要重复使用相同的Set来添加考试。

在循环内声明变量。

for(Term t: set_terms) { 
  Set<Exam> new_exams = new HashSet<>();

  for(Exam e: exams) {
    // ...
  }

  t.setExams(new_exams);
}