scalalistbuffer

Comparing the elements in a ListBuffer


I have two ListBuffers:

  import scala.collection.mutable._

  val lstbufWhichChange = ListBuffer("Core", "One", "Zero", "Right", "Top", "Else")
  val lstbufStatic = ListBuffer("Core", "Right", "Left", "Zero", "One", "Two", "Top", "Bottom", "Else")

The lstbufWhichChange is a subset of lstbufStatic. What I am trying to do is, finding a way to compare these two collections, if lstbufWhichChange has the elements in the same order like the lstbufStatic even if it doesn't contains all of them (it's a subset). How I can do it?


Solution

  • One way to do using built in functions can be: First get the common elements in both the list

      val commonEle = lstbufWhichChange.intersect(lstbufStatic)
    

    After that, get the elements from lstbufStatic which are present in the commonEle list

      val list = lstbufStatic.filter(e => commonEle.contains(e))
    

    list should be equal to the commonEle list.

    In the example you provided, lstbufWhichChange has Right after one, hence, commonEle.equals(list) will return false. But if you swap those elements then it will return true.