w3resource

Scala Programming: Check list contains a sublist


Write a Scala program to check whether a list contains a sublist.

Sample Solution:

Scala Code:

object Scala_List {    
  def test_sublist[A](list1:List[A], list2:List[A]):Boolean = {
      list1.forall(list2.contains)
    }  
  def main(args: Array[String]): Unit = {
     println(test_sublist(List(1,2), List(1,2,3,4)))
     println(test_sublist(List(1,2), List(1,3,4,2)))
     println(test_sublist(List(1,2), List(1,3,4)))
    }
}

Sample Output:

true
true
false

Go to:


PREV : Write a Scala program to add each element n times to a given list of integers.
NEXT : Write a Scala program to count the number of occurrences of each element in a given list.

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.