krishna.kadigari
krishna.kadigari

Reputation: 87

get list of all matching string from another list of strings in scala

In Scala how to get a list of all strings which match one of the patterns in another string. for example, I have two lists

lst1=["a/b/d=20180103","a/c/d=20180201","a/c/d=20180102","a/e/d=20180104","a/b/d=20180203"]

lst2 = ["20180102", "20180103", "20180104"]

now I need the intersection of list1 which match patterns from list2.

expected output:

["a/b/d=20180103", "a/c/d=20180102","a/e/d=20180104"]

Upvotes: 0

Views: 860

Answers (3)

jwvh
jwvh

Reputation: 51271

Why not just filter it?

lst1.filter(s => lst2.exists(s.contains))

Upvotes: 2

Leo C
Leo C

Reputation: 22439

You can use collect on the first list with a case partial function that retains those elements whose date substring is in the second list:

val lst1 = List("a/b/d=20180103", "a/c/d=20180201", "a/c/d=20180102", "a/e/d=20180104", "a/b/d=20180203")
val lst2 = List("20180102", "20180103", "20180104")

lst1.collect{ case s if lst2.contains(s.split("=").last) => s }
// res1: List[String] = List(a/b/d=20180103, a/c/d=20180102, a/e/d=20180104)

Upvotes: 0

zenwraight
zenwraight

Reputation: 2000

You can achieve this using simple for loop in scala i.e using a map on both the lists.

Have a look at the code below for a better understanding:-

val lst1 =List("a/b/d=20180103","a/c/d=20180201","a/c/d=20180102","a/e/d=20180104","a/b/d=20180203")

val lst2 = List("20180102", "20180103", "20180104")

val ans = lst1.map { value =>
  val firstPart = value.split('=').head
  val secondPart = value.split('=').last
  if(lst2.contains(secondPart)) {
    value
  } else {
    None
  }
}

ans.filter(_ != None)

Hope this helps!

Upvotes: 0

Related Questions