0

If I have

val incomingIds : List[Int] = ....
val existingIds : List[Int] = //this makes db calls and find existing records (only interested in returning ids)

Now next I want to compare incomingIds with existingIds in a following way

say I have

val incomingIds : List[Int] = List(2,3,4,5)
val existingIds : List[Int] = List(1,2,3,6)

What above sample suggests is that my API should be able to find ids that are subject for deletion (ones that exist in incomingIds but not in existingIds). In this sample existingIds have 1,4,5 but they aren't there in incomingIds means 1,4,5 should go into

val idsForDeletion :List[Int]

and there will be another list call it

val idsForInsertion :List[Int]. 

so 6 should go into idsForInsertion list.

Is there a simple way to partition lists such a way?

Govind Singh
  • 15,282
  • 14
  • 72
  • 106
user2066049
  • 1,371
  • 1
  • 12
  • 26
  • I think what you're technically looking for here is symmetric difference of sets. It would be way easier to use `Set[A]` here: `(s1 diff s2, s2 diff s1)`. – Patryk Ćwiek Oct 20 '14 at 18:56

2 Answers2

6

You can filter the items from each list that aren't included in the other one using scala's filterNot function:

val idsForDeletion = existingIds.filterNot(incomingIds.toSet)
val idsForInsertion = incomingIds.filterNot(existingIds.toSet)
Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
5

you can use diff

def diff(that: collection.Seq[A]): List[A]

It Computes the multiset difference between this list and another sequence.

scala> val incomingIds : List[Int] = List(2,3,4,5)
incomingIds: List[Int] = List(2, 3, 4, 5)

scala> val existingIds : List[Int] = List(1,2,3,6)
existingIds: List[Int] = List(1, 2, 3, 6)

scala> (incomingIds diff existingIds).toSet
res1: scala.collection.immutable.Set[Int] = Set(4, 5)

scala> (existingIds diff incomingIds).toSet
res2: scala.collection.immutable.Set[Int] = Set(1, 6)
Govind Singh
  • 15,282
  • 14
  • 72
  • 106