使用Kotlin将序列分散到三个列表的习惯性方法 [英] Idiomatic way to spilt sequence into three lists using Kotlin
问题描述
我有一系列的项目,它们是三批次的,所以流可能看起来像
1,a,+,2,b,*,3,c,& .......
我想要做的就是把它分成三个列表,目前我通过分成两个列表来完成这个列表,一个列表包含数字,另一个列出所有其他列表,然后把结果的后半部分,字母和符号再次分割成字母和符号,因此我最终得到了三个列表。
这让我觉得有点效率低下,也许一种功能性方法并不是最好的方法。
有没有这样做的有效方法,是我的选择,还是for循环?
感谢
val elementsByType = sequence.groupBy {getElementType(it) }
其中 getElementType
是返回类型的函数元素:是字母,数字还是符号。这个函数可能会返回一个数字,比如1,2,3,或者一些枚举值与3个不同的条目。
groupBy
从元素类型返回一个映射到该类型元素的列表。
So this is possibly more about functional programming than Kotlin, I am at that stage were a little knowledge is dangerous, and I wrote the app in Kotlin so seems fair to ask a Kotlin question as its Kotlins structures that i am interested in.
I have a sequence of items, they are in batches of three, so the stream may look like
1,a,+,2,b,*,3,c,&.......
What I want to do is to spilt this into three lists, currently I am doing this by partitioning into two lists, one that contains the numbers and one that contains everything else, then taking the second half of the result, the letters and symbols and partitioning again, into letters and symbols, thus i end up with three lists.
This strikes me as somewhat inefficient, maybe a functional approach isn't the best approach here.
Is there an efficient way of doing this, are my choices, this or a for loop?
Thanks
You can use groupBy
method to group elements of your sequence by an element type:
val elementsByType = sequence.groupBy { getElementType(it) }
where getElementType
is function returning a type of the element: whether it is a letter, or a number, or a symbol. This function may return either a number, such as 1, 2, 3, or a value of some enum with 3 different entries.
groupBy
returns a map from element type to list of elements of that type.
这篇关于使用Kotlin将序列分散到三个列表的习惯性方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!