【问题标题】:How do I write to one file a K from one Map, and a V from another?如何将一个地图中的 K 和另一个地图中的 V 写入一个文件?
【发布时间】:2020-04-07 16:44:56
【问题描述】:

我需要将一个映射中的所有键写入一列中,并将不同映射中的所有值写入下一列。

我可以使用此代码单独执行任一列,但是当我结合时,我该如何解释这个(?),如果我有 10 个键和 10 个值,这些键将重复每个键的 10 个。

我需要对我的循环做些什么?

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();
}

因此,根据下面的 cmets,我对此进行了编辑:

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

但是,这会写入一个空文件。

【问题讨论】:

    标签: java treemap filewriter printwriter linkedhashmap


    【解决方案1】:

    试试这个。它确实假定每个映射中的映射条目数是相同的。 否则,您将获得索引越界异常,或者您不会打印所有值。

          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();
    

    【讨论】:

    • 这绝对是它!感谢您对此事的帮助。
    【解决方案2】:

    您不需要嵌入式循环。您可以通过第一个地图中的键进行迭代并从第二个地图中获取值:

    for (String courseKey: courses.keySet())
       String count = countStudents.get(courseKey);
       // ... output courseKey and count to file
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-02
      • 1970-01-01
      • 2022-01-08
      • 2021-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-24
      • 2020-01-23
      相关资源
      最近更新 更多