zork
zork

Reputation: 2135

Scala: difference of two sets by key

I have two sets of (k,v) pairs:

val x = Set((1,2), (2,10), (3,5), (7,15))
val y = Set((1,200), (3,500))

How to find difference of these two sets by keys, to get:

Set((2,10),(7,15))

Any quick and simple solution?

Upvotes: 1

Views: 879

Answers (3)

Rex Kerr
Rex Kerr

Reputation: 167911

val ym = y.toMap
x.toMap.filterKeys(k => !(ym contains k)).toSet

Sets don't have keys, maps do. So you convert to map. Then, you can't create a difference on maps, but you can filter the keys to exclude the ones you don't want. And then you're done save for converting back to a Set. (It's not the most efficient way to do this, but it's not bad and it's easy to write.)

Upvotes: 3

Hackaholic
Hackaholic

Reputation: 19763

you can try this one:

 x filter{ m => y map{_._1} contains m._1} toSet

Upvotes: 0

elm
elm

Reputation: 20435

Let val keys = y.map(_._1).toSet be the set of keys (first element in the pair) that must not occur as key in x; thus

for ( p <- x if !keys(p._1) ) yield p

as well as

x.collect { case p@(a,b) if !keys(a) => p }

and

x.filter ( p => !keys(p._1) )
x.filterNot ( p => keys(p._1) )

Upvotes: 2

Related Questions