Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - how to find number of repeated values in a list?

I have a list, e.g like:

val list = listOf("orange", "apple", "apple", "banana", "water", "bread", "banana") 

How can i check how many times apple is duplicated in this list?

like image 892
K.Os Avatar asked Nov 09 '17 11:11

K.Os


People also ask

How do you use Distinctby in Kotlin?

The elements in the resulting list are in the same order as they were in the source array. Returns a list containing only elements from the given array having distinct keys returned by the given selector function. The elements in the resulting list are in the same order as they were in the source array.


2 Answers

One way to find all the repeated values in a list is using groupingBy and then filter the values which are > 1. E.g.

  val list = listOf("orange", "apple", "apple", "banana", "water", "bread", "banana") println(list.groupingBy { it }.eachCount().filter { it.value > 1 })  

Output

{apple=2, banana=2} 
like image 126
sol4me Avatar answered Sep 18 '22 17:09

sol4me


list.count { it == "apple" } 

Documentation: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/, https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/count.html

like image 26
JB Nizet Avatar answered Sep 20 '22 17:09

JB Nizet