I have a List of Lists, in which I need to count the consecutive occurrences of a given element.
The list is structured as follows:
List[List[Attendance]]
Attendance(val scheduleId: Long,
val date: LocalDate,
val teamId: Long,
val memberId: Long,
var attendance: AttendanceType)
I need to check the number of times a given element in the list has AttendanceType == In
is followed by the same AttendanceType == In
.
I have seen people use containsSlice()
and Seq(x, y)
for checking that this occurs once, but not counting the number of times it happens.
Something like this?
def countSeqDup(l: List[List[Attendance]], in: AttendanceType): Int =
l.flatten.sliding(2).count{ x => x(0).attendance == in && x(1).attendance == in}
The flatten
creates a single list of values and sliding
groups them in adjacent pairs, so then it is just a question of counting pairs that match.
Note that this will fail if there are fewer than 2 elements in total.