GameOfThrows
GameOfThrows

Reputation: 4510

scala partial string match

I have a question about List of Strings partial Matching to a List of Strings (intersect I guess).

List1:List = [a,b,c,d,e,f]
List2:Iterable[String] = [a b,e f,g h,x y]

I want to take any element or combination of elements in List1 that also happens to be in List2, and replace it with the element in List2, for example, [a,b] are in List1, List 2 contains element [a b], in this case, [a,b] in List1 will be replaced with [a b]. The result for List 1 should be:

List1result = [a b,c,d,e f] 

I've tried intersect, which would return [a b, e f]

Upvotes: 0

Views: 1285

Answers (2)

curious
curious

Reputation: 2928

You can try something like this :

  val l1 = List("a", "b", "c", "d", "e", "f")

  val l2 = List("a b", "e f", "g h", "x y")

  l1.filterNot(x=>l2.flatten.filter(_ != ' ').contains(x.toCharArray.head))

 l2.foldLeft(List[String]()) { case (x, y) => if (l1.containsSlice(y.split(" "))) x :+ y else x} ++ 
l1.filterNot(x=>l2.flatten.filter(_ != ' ').contains(x.toCharArray.head))


l1: List[String] = List(a, b, c, d, e, f)
l2: List[String] = List(a b, e f, g h, x y)
res0: List[String] = List(a b, e f, c, d)

Upvotes: 1

Makis Arvanitis
Makis Arvanitis

Reputation: 1195

Ok, I edited my answer after the comment bellow, I think I understood the question now.

take each element of the second list, convert it into a list of elements and use containsSlice to filter out the value.

containsSlice will return true if all the elements in the slice are present in the first list.

val lst1 = List("a","b","c","d","e","f")
val lst2 = List("a b","e f","g h","x y")

lst2.filter{ pair =>
  val xss = pair.split(" ")
  lst1.containsSlice(xss)
}

Upvotes: 1

Related Questions