1

Is there some predefined function in Scala to split list into several lists by some logic? I found grouped method, but it doesn't fit my needs.

For example, I have List of strings: List("questions", "tags", "users", "badges", "unanswered").

And I want to split this list by max length of strings (for example 12). In other words in each resulting chunk sum of the length of all strings should not be more than 12:

List("questions"), List("tags", "users"), List("badges"), List("unanswered")

EDIT: I'm not necessarily need to find the most optimal way of combining strings into chunks, just linear loop which checks next string in list, and if its length doesn't fit to required (12) then return current chunk and next string will belong to next chunk

1

2 Answers 2

7

There is no buildIn mechanism to do that, that I know of, but you could achieve something like that with a foldLeft and bit of coding:

val test = List("questions", "tags", "users", "badges", "unanswered")

test.foldLeft(List.empty[List[String]]) {
  case ((head :: tail), word) if head.map(_.length).sum + word.length < 12 =>
    (word :: head) :: tail
  case (result, word) =>
    List(word) :: result
}

-> res0: List[List[String]] = List(List(unanswered), List(badges), List(users, tags), List(questions))
Sign up to request clarification or add additional context in comments.

1 Comment

if order is important you should reverse result after fold like this result.map(_.reverse).reverse
1

If you can make reasonable assumptions about the max length of a string (e.g. 10 characters), you could then use sliding which is much faster for a long list:

val elementsPerChunk = ???   // do some maths like 
                             // CHUNK_SIZE / MAX_ELEM_LENGTH
val test = List("questions", "tags", "users", "badges", "unanswered")
test.sliding(elementsPerChunk, elementsPerChunk).toList

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.