w3resource

Scala Programming: Check list contains a sublist

Scala Programming List Exercise-21 with Solution

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

Scala Code Editor :

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

Previous: 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.

What is the difficulty level of this exercise?