'Count based on hash map class value
I have a hash map of type:
val studentById: <Int, StudentDetails>
StudentDetails has columns such as: ActiveCourse and CourseID. I would like to count number of students that have taken each course. So for every courseID that is in all StudentDetails, group and count number of students linked to it where ActiveCourse is true. Is it possible to do something like:
studentById.mapValues{
it.values.groupBy{ courseId}.countEach student id where activeCourse is true.
}
The end result should be something like:
coursesCountStudents <Int (courseId), Int (number of active students)>
Solution 1:[1]
You can apply operations to groups created when using the groupingBy operation. It seems like Grouping? will be what you want.
Solution 2:[2]
I am assuming the StudentDetails
contains a list of courses.
fun countCourses(students: Map<Int, StudentDetails>): Map<Int, Int>
{
val coursesCountStudents = mutableMapOf<Int, Int>()
students.forEach { (studentId, details) ->
// I'm using a stream here so we only iterate over the array once during the filtering and processing steps
details.courses.stream()
.filter { it.ActiveCourse }
.forEach {
coursesCountStudents[it.courseId] = coursesCountStudents[it.courseId]?.inc() ?: 1
}
}
}
return coursesCountStudents
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Hampus |
Solution 2 | flamewave000 |