Reputation: 45
I have this ArrayList in Kotlin :
a = ArrayList<String>()
a.add("eat")
a.add("animal")
a.add("internet")
And I would like to sort the elements of my ArrayList by frequency of "e" eg I would like to have a new ArrayList such as :
a[0] = "animal" // there is no e in animal
a[1] = "eat" // there is one e in animal
a[2] = "internet" // there is two e in internet
I thought to use Collections.sort(a) but like my sort is specific it won't work...
Do you have any ideas ?
Thank you !
Upvotes: 1
Views: 257
Reputation: 89568
You can also do this without converting each String
to a CharArray
first (as in the currently the accepted answer), which I don't know why you'd do:
a.sortBy { it.count { it == 'e' } }
Plus, you might want to name nested it
s:
a.sortBy { word -> word.count { character -> character == 'e' } }
Upvotes: 3
Reputation: 2719
Writing on my phone so the syntax might not be exactly correct, but something like:
a.sortBy { it.toCharArray().count { it == 'e' } }
Upvotes: 2