
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Number of Repeated Values in a Kotlin List
In this article, we will see how to find the number of repeated values in a Kotlin list.
Example – Finding Repeated Values Using groupingBy()
The Kotlin library provides an inline function called groupingBy() which creates a grouping source from an array to be used later with one of the group-and-fold operations using the specified keySelector function to extract a key from each element.
The function declaration of groupingBy() looks like this −
inline fun <T, K> Array<out T>.groupingBy( crossinline keySelector: (T) -> K ): Grouping<T, K>
In this example, we will create a list of values and implement groupingBy() in the list.
fun main(args: Array<String>) { val mylist = listOf("C", "Java", "C#", "Java", "C", "C#", "SQL") println(mylist.groupingBy { it }.eachCount().filter { it.value >= 1 }) }
Output
It will produce the following output −
{C=2, Java=2, C#=2, SQL=1}
Example – Finding Repeated Values Using count()
Another way to find the number of repeated elements in a Kotlin list is by using the count() function. In this example, we will modify the above code to generate the number of times each value appears in the List.
fun main(args: Array<String>) { val mylist = listOf("C", "Java", "C#", "Java", "C", "C#", "SQL") println("Input List: " + mylist) println("Count of C: " + mylist.count{it == "c"}) println("Count of Java: " + mylist.count{it == "Java"}) println("Count of C# : " + mylist.count{it == "C#"}) println("Count of SQL: " + mylist.count{it == "SQL"}) }
Output
It will produce the following output −
Input List: [C, Java, C#, Java, C, C#, SQL] Count of C: 0 Count of Java: 2 Count of C# : 2 Count of SQL: 1