使用Kotlin将序列分散到三个列表的习惯性方法 [英] Idiomatic way to spilt sequence into three lists using Kotlin

查看:138
本文介绍了使用Kotlin将序列分散到三个列表的习惯性方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这可能更多的是关于函数式编程而不是Kotlin,我在那个阶段有一点知识是危险的,而且我在Kotlin编写了这个应用程序,所以,把Kotlin问题当作我感兴趣的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆