Home > Blockchain >  Count based on hash map class value
Count based on hash map class value

Time:05-11

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

CodePudding user response:

You can apply operations to groups created when using the groupingBy operation. It seems like Grouping will be what you want.

CodePudding user response:

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
}
  • Related