Idiomatic way to spilt sequence into three lists u

2019-05-20 13:08发布

问题:

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

回答1:

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.