0

I need to write to csv all the keys from one map in one column, and all the values from a different map in the next column.

I can do either column individually with this code but when I combine, how do I explain this(?), if I have 10 keys and 10 values the keys will repeat 10 of each key.

What do I need to do to my loops?

private static void generateCourseCounts() throws IOException {     
    ArrayList<StudentCourse> lsc = loadStudentCourses();
    Map<Integer, Integer> countStudents = new TreeMap<Integer, Integer>();
    for (StudentCourse sc : lsc) {
        Integer freq = countStudents.get(sc.getCourseId());
        countStudents.put(sc.getCourseId(), (freq == null) ? 1 : freq + 1);
    }
    ArrayList<Course> lc = loadCourses();
    Map<String, String> courses = new LinkedHashMap<String, String>();
    for (Course c : lc) {
        String freq = courses.get(c.getCourseName());
        courses.put(c.getCourseName(), freq);
    }
    FileWriter writer = new FileWriter("CourseCounts.csv");
    PrintWriter printWriter = new PrintWriter(writer);
    printWriter.println("Course Name\t# Students");
    for (Entry<String, String> courseKey : courses.entrySet()) 
    for (Entry<Integer, Integer> numberKey : countStudents.entrySet()) {
        printWriter.println(courseKey.getKey() + "\t" + numberKey.getValue());
    }
    printWriter.close();
    writer.close();
}

So, as per comments below, I edited to this:

for (String courseKey : courses.keySet()) {
    Integer count = countStudents.get(courseKey) ;
    printWriter.println(courseKey + "\t" + count); 
    }

However, this writes an empty file.

2 Answers2

0

You don't need embedded cycles. You can just iterate by keys from 1st map and get values from 2nd:

for (String courseKey: courses.keySet())
   String count = countStudents.get(courseKey);
   // ... output courseKey and count to file
}
Petr Aleksandrov
  • 1,434
  • 9
  • 24
0

Try this. It does presume that the number of map entries in each map is the same. Otherwise, you will either get an index out of bounds exception or you won't print all the values.

      int i = 0;
      Integer[] counts = countStudents.values().stream().toArray(Integer[]::new);
      for (String courseKey : courses.keySet()) {
         printWriter.println(courseKey + "\t" + counts[i++]);
      }
      printWriter.close();
      writer.close();
WJS
  • 36,363
  • 4
  • 24
  • 39