Is there any efficient way of removing elements present in Seq one from Seq two
val one = Seq("A", "B")
val two = Seq("A", "B", "C", "E", "F")
val out = two.map {
for (n <-one){
_.filterNot(_ == n)
}
}
expected output Seq("C", "E", "F") , empty or null of one should also be handled
But I'm getting error Cannot resolve overloaded method 'map'
can anyone suggest what am doing wrong here ?
This is the simplest way to do this efficiently:
two.filterNot(one.toSet.contains)
This uses contains to see whether an item is in one or not. one is converted to a Set as this implements contains more efficiently that Seq which does a linear search.
Related
Given a constant value and a potentially long Sequence:
a:String = "A"
bs = List(1, 2, 3)
How can you most efficiently construct a Sequence of tuples with the first element equalling a?
Seq(
( "A", 1 ),
( "A", 2 ),
( "A", 3 )
)
Just use a map:
val list = List(1,2,3)
list.map(("A",_))
Output:
res0: List[(String, Int)] = List((A,1), (A,2), (A,3))
Since the most efficient would be to pass (to further receiver) just the seq, and the receiver tuple the elements there, I'd do it with views.
val first = "A"
val bs = (1 to 1000000).view
further( bs.map((first, _)) )
You can do it using map just like in the answer provided by #Pedro or you can use for and yield as below:
val list = List(1,2,3)
val tuple = for {
i <- list
} yield ("A",i)
println(tuple)
Output:
List((A,1), (A,2), (A,3))
You are also asking about the efficient way in your question. Different developers have different opinions between the efficiency of for and map. So, I guess going through the links below gives you more knowledge about the efficiency part.
for vs map in functional programming
Scala style: for vs foreach, filter, map and others
Getting the desugared part of a Scala for/comprehension expression?
I have two Scala lists with the same number and type of elements, like so:
val x = List("a", "b", "c")
val y = List("1", "2", "3")
The result I want is as follows:
List("a1", "b2", "c3")
How can this be done in Scala? I could figure this out using mutable structures but I think that would be unidiomatic for Scala.
Combine zip and map:
x zip y map { case (a, b) => a + b }
Strangely enough, this also works:
x zip y map (_.productIterator.mkString)
but I would strongly prefer the first version.
I need check sequence contains another sequence, but based on one field only:
case class Test(f1: Int, f2: String)
val seq = Seq(Test(1, "a"), Test(2, "b"), Test(3, "a"), Test(4, "c"))
Now i want to have something like(theoretical not working code):
seq.containsSlice(Seq(Test(2, _), Test(3, _))) shouldBe true
Where second field can be any.
My idea - create another class, based on Test, where equals/hashcode uses only one field, and convert my Seq[Test] to Seq[TestWithOneField]. May be there is more elegant and universal solution?
You could map the sequence to obtain a sequence only of the fields you are checking (in this case a sequence of the integers in the f1 field):
seq.map(_.f1).containsSlice(Seq(2,3))
I have two lists
val list1 = List((List("AAA"),"B1","C1"),(List("BBB"),"B2","C2"))
val list2 = List(("AAA",List("a","b","c")),("BBB",List("c","d","e")))
I want to match first element from list2 with first element of list1 and get combined list.
I want output as -
List((List("AAA"),"B1","C1",List("a","b","c")))
How to get above output using Scala??
This is what I came up with:
scala> val l1 = List((List("AAA"),"B1","C1"),(List("BBB"),"B2","C2"))
l1: List[(List[String], String, String)] = List((List(AAA),B1,C1), (List(BBB),B2,C2))
scala> val l2 = List((List("AAA"), List("a", "b", "c")), (List("BBB"), List("c", "d", "e")))
l2: List[(String, List[String])] = List((AAA,List(a, b, c)), (BBB,List(c, d, e)))
scala> l1.collectFirst {
| case tp => l2.find(tp2 => tp2._1.head == tp._1.head).map(founded => (tp._1, tp._2, tp._3, founded._2))
| }.flatten
res2: Option[(List[String], String, String, List[String])] = Some((List(AAA),B1,C1,List(a, b, c)))
You can use collectFirst to filter values you don't want and on every tuple you use find on the second list and map it into the tuple you want.
A couple of notes, this is horrible, I don't know how you got with a Tuple4 in the first place, I personally hate all that tp._* notation, it's hard to read, think about using case classes to wrap all that into some more manageable structure, second I had to use .head which in case of empty list will throw an exception so you may want to do some checking before that, but as I said, I would completely review my code and avoid spending time working on some flawed architecture in the first place.
You can use zip to combine both the list
val list1 = List((List("AAA"),"B1","C1"),(List("BBB"),"B2","C2"))
val list2 = List(("AAA",List("a","b","c")),("BBB",List("c","d","e")))
val combinedList = (list1 zip list2)
combinedList.head will give you the desired result
It will give the combined list from which you can get the first element
Suppose I have two arrays:
val ar1 = Array[String]("1", "2", "3")
val ar2 = Array[String]("1", "2", "3", "4")
Now for each element of ar1, I want to first concatenate that element with the corresponding element of ar2, and then print the result. One way to do would be something like:
List.range(0, ar1.size).foreach(i => println(ar1(i)+ar2(i)))
It would have been nicer if there was a foreach variant that would allow me to work directly with the indices of ar1 instead of first constructing the integer list.
Perhaps there is a better way?
One very convenient way to do this is with the zipped method on tuples. Put two collections in, get out two arguments to a function!
(ar1,ar2).zipped.foreach((x,y) => println(x+y))
This is both convenient to write and fast, since you don't need to build a tuple to store each pair (as you would with (ar1 zip ar2)) which you then have to take apart again. Both forms of zip stop when the shorter of the two collections is exhausted.
If you have something more complicated (e.g. you need to do math on the index), the canonical solution is to zip in the index:
ar1.zipWithIndex.foreach{ case(x,i) => println(x+ar2(i)) }
The method you are using is more rapidly and compactly done as follows, an can be useful:
ar1.indices.foreach(i => println(ar1(i)+ar2(i)))
although this only works if the first collection is no longer than the second. You can also specify your ranges explcitly:
(0 until (ar1.size min ar2.size)).foreach(i => println(ar1(i)+ar2(i)))
to get around this problem. (You can see why zip and zipped are preferred unless what you're doing is too complicated for this to work easily.)
If it is not a parallel collection (and usually it is not unless you call .par), it's also possible, though not recommended, to keep track with a mutable variable:
{ var i=-1; ar1.foreach{ x => i += 1; println(x+ar2(i)) } }
There are a very limited number of cases where this is necessary (e.g. if you may want to skip or backtrack on some of the other collection(s)); if you can avoid having to do this, you'll usually end up with code that's easier to reason about.
This is how you loop with an index in idiomatic Scala:
scala> List("A", "B", "C").zipWithIndex foreach { case(el, i) =>
| println(i + ": " + el)
| }
0: A
1: B
2: C
And here is the idiomatic Scala way to do what you are trying to achieve in your code:
scala> val arr1 = Array("1", "2", "3")
arr1: Array[java.lang.String] = Array(1, 2, 3)
scala> val arr2 = Array("1", "2", "3", "4")
arr2: Array[java.lang.String] = Array(1, 2, 3, 4)
scala> (arr1, arr2).zipped.map(_ + _) foreach println
11
22
33
I did not had the opportunity to test it, but this should do the trick:
ar1.zip(ar2).foreach(x => println(x._1 + x._2))
zip will do it:
ar1 zip ar2 foreach { p => println(p._1 + p._2) }
This will yield:
11
22
33
Note that you don't need [String] generic type, will be infered by the compiler:
val ar1 = Array("1", "2", "3")
val ar2 = Array("1", "2", "3", "4")