-3

How can I sort Scala Seq according to the order of values present in another Seq?

val original_seq = Seq("a", "b", "c", "d", "e", "f", "g")  //[a,b,c,d,e,f,g]
val original_set = original_seq.toSet
val entity_set = Seq("a", "b", "d", "f").toSet  //[a,b,d,f]
val delta_set = original_set.diff(entity_set)
val final_cols = entity_set ++ delta_set.toSeq  //[e f a b g c d] or some random order
//Expected order of final_cols Seq is ==> [a,b,c,d,e,f,g]

final_cols Seq I want to be sorted as values in original_seq? How can this be done in Scala?

vishalraj
  • 105
  • 2
  • 11

2 Answers2

0

You could do something like this (invalid entries will go to the end):

val originalSeq = Seq("a", "b", "c", "d", "e", "f", "g") 
val positionMap = originalSeq.zipWithIndex.toMap

val input = Seq("d", "f", "a", "g", "c")

input.sortBy(x => positionMap.getOrElse(x, positionMap.size))
Thilo
  • 257,207
  • 101
  • 511
  • 656
0

Use a LinkedHashSet (source code). It's a set that preserves order of items, by the order in which they were added, effectively de-duplicating your sequence by ignoring/removing items that have already appeared.

import scala.collection.mutable.LinkedHashSet
val original:LinkedHashSet[String] = LinkedHashSet() ++ originalSeq
val entity:Set[String] = Set("a", "b", "d", "f")

// diff will be Set(c, e, g)
val diff:LinkedHashSet[String] = original &~ entity

// finalItems will be LinkedHashSet[String] = Set(a, b, d, c, f, e, g)
val finalItems:LinkedHashSet[String] = original & (diff ++ entity)
// Note above, the entity ++ diff yields the same result as long as
// original comes first

However, I'm not sure why you would want to add the difference of a set and some subset of the set, back to that subset. You would always get the original set back. In other words, B ⊆ A => B ∪ (A ∖ B) = A.

Maybe what you want is this (just the subset entity to be ordered)?

// result is: LinkedHashSet[String] = Set(a, b, d, f)
original & entity
ELinda
  • 2,658
  • 1
  • 10
  • 9