0

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]

2
  • 3
    "I want to replace any element" with what ? -- "any element in List1 that also happens to be in List2" but 'c' and 'd' are not in List2 ? Commented Apr 9, 2015 at 11:48
  • sorry, I meant to replace elements in List 1 that shares the same String as in List 2. I have amended the question Commented Apr 9, 2015 at 11:57

2 Answers 2

1

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

list2 does not have "a","b". It has "a b". OP wants to replace "a","b" in list1 with "a b"
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.