St.Antario
St.Antario

Reputation: 27425

Split Set into multiple Sets Scala

I have some Set[String] and a number devider: Int. I need to split the set arbitrary by pieces each of which has size devider. Examples:

1.

Set: "a", "bc", "ds", "fee", "s"
devider: 2
result: 
    Set1: "a", "bc"
    Set2: "ds", "fee"
    Set3: "s"

2.

Set: "a", "bc", "ds", "fee", "s", "ff"
devider: 3
result: 
    Set1: "a", "bc", "ds"
    Set2: "fee", "s", "ff"

3.

Set: "a", "bc", "ds"
devider: 4
result: 
    Set1: "a", "bc", "ds"

What is the idiomatic way to do it in Scala?

Upvotes: 8

Views: 1239

Answers (2)

ishwar
ishwar

Reputation: 298

This is possible only if it is a List like:

val pn=List("a", "bc", "ds", "fee", "s").grouped(2).toSet
println(pn)

Upvotes: 1

jwvh
jwvh

Reputation: 51271

You probably want something like:

Set("a", "bc", "ds", "fee", "s").grouped(2).toSet

The problem is that a Set, by definition, has no order, so there's no telling which elements will be grouped together.

Set( "a", "bc", "ds", "fee", "s").grouped(2).toSet
//res0: Set[Set[String]] = Set(Set(s, bc), Set(a, ds), Set(fee))

To get them grouped in a particular fashion you'll need to change the Set to one of the ordered collections, order the elements as required, group them, and transition everything back to Sets.

Upvotes: 21

Related Questions