Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get size of specfic value inside array Kotlin

Tags:

kotlin

here is example of the list. I want to make dynamic where maybe the the value will become more.

val list = arrayListOf("A", "B", "C", "A", "A", "B") //Maybe they will be more 

I want the output like:-

val result = list[i] + " size: " + list[i].size

So the output will display every String with the size.

A size: 3
B size: 2
C size: 1

If I add more value, so the result will increase also.

like image 484
Ticherhaz FreePalestine Avatar asked Dec 06 '25 05:12

Ticherhaz FreePalestine


2 Answers

You can use groupBy in this way:

val result = list.groupBy { it }.map { it.key to it.value.size }.toMap()

Jeoffrey's way is better actually, since he is using .mapValues() directly, instead of an extra call to .toMap(). I'm just leaving this answer her since I believe that the other info I put is relevant.

This will give a Map<String, Int>, where the Int is the count of the occurences.

This result will not change when you change the original list. That is not how the language works. If you want something like that, you'd need quite a bit of work, like overwriting the add function from your collection to refresh the result map.

Also, I see no reason for you to use an ArrayList, especially since you are expecting to increase the size of that collection, I'd stick with MutableList if I were you.

like image 92
AlexT Avatar answered Dec 10 '25 15:12

AlexT


I think the terminology you're looking for is "frequency" here: the number of times an element appears in a list.

You can usually count elements in a list using the count method like this:

val numberOfAs = list.count { it == "A" }

This approach is pretty inefficient if you need to count all elements though, in which case you can create a map of frequencies the following way:

val freqs = list.groupBy { it }.mapValues { (_, g) -> g.size }

freqs here will be a Map where each key is a unique element from the original list, and the value is the corresponding frequency of that element in the list.

This works by first grouping elements that are equal to each other via groupBy, which returns a Map<String, List<String>> where each key is a unique element from the original list, and each value is the group of all elements in the list that were equal to the key. Then mapValues will transform that map so that the values are the sizes of the groups instead of the groups themselves.

An improved approach, as suggested by @broot is to make use of Kotlin's Grouping class which has a built-in eachCount method:

val freqs = list.groupingBy { it }.eachCount()
like image 22
Joffrey Avatar answered Dec 10 '25 15:12

Joffrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!