晚上好,

我试图找出是否有可能在某些课程的数组内计数。这是我下面的例子。

例:

list.add(new Student(" Bourne", "70","\tCOP2250, ENC3250, COP3530"));
list.add(new Student(" Gracia", "50","\tCOP2250, COP3250, COP4250"));


Output:

COP2250 - 2
COP3530 - 1
ENC3250 - 1


输出应与上面类似。让我知道是否可以这样做,否则我将需要单独对课程进行排序。

在此先感谢您的支持。

最佳答案

您可以使用以下方式:

Map<String, Integer> cources = new HashMap<>();
for (Student s : list) {
    //I assumed that eg. "\tCOP2250, ENC3250, COP3530" is in a (public) variable Cources
    //in your Student class. You can replace this by a getter or whatever you need.
    for (String name : s.Courses.replace("\t", "").split(", ")) {
        if (cources.containsKey(name))
            cources.replace(name, cources.get(name)+1);
        else
            cources.put(name, 1);
    }
}
//some output for testing
cources.forEach((a, b) -> System.out.println(a + " - " + b));

07-24 20:34