2
votes

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
Can you provide you current code please?voddan
@voddan The question is an abstraction of the issue I am having in code, I prefer to write questions that way, if i can. The answer I was looking for is groupBy, as stated below, if you are still interested in the code i will be happy to edit the question.Gavin

1 Answers

5
votes

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.