Reputation: 143
I am trying to concatenate scala list in loop using below code.
var names: List[String] = Nil
val cluster_id = List("149095311_0", "149095311_1")
for (id <- cluster_id) {
val influencers_name = searchIndex(s"id : $id", "id", "influencers", searcher)
println("In Loop " + influencers_name)
names :::= influencers_name
}
for(n <- names) println("List element -> " + n)
But when I iterate over final list it give me individual list's instead of individual elements of concatenated List.
Below is the O/P of above code:
In Loop List(kroger 10TV DispatchAlerts)
In Loop List(kroger seanhannity SenTedCruz)
List element -> kroger seanhannity SenTedCruz
List element -> kroger 10TV DispatchAlerts
Upvotes: 2
Views: 732
Reputation: 1544
Your code isn't very functional in that you are mutating variables. The following is more elegant:
def searchIndex(s: String): List[String] = {
if (s == "149095311_0") List("kroger 10TV DispatchAlerts")
else List("kroger seanhannity SenTedCruz")
}
val cluster_id = List("149095311_0", "149095311_1")
val names = cluster_id.foldLeft(List[String]()) {
(acc, id) => acc ++ searchIndex(id)
}
for(n <- names) println("List element -> " + n)
Where '++' is used to concatenate the elements of two lists.
Upvotes: 1
Reputation: 3863
It looks like the problem is in searchIndex method that is retreiving a List[String] with a single String that contain all the values separated by a space, fix that method to make sure that it retrieves a List with one elemente per value.
To check if this is right try this, this is just a workaround, you should fix searchIndex
var names: List[String] = Nil
val cluster_id = List("149095311_0", "149095311_1")
for (id <- cluster_id) {
val influencers_name = searchIndex(s"id : $id", "id", "influencers", searcher).flatMap(_.split(' '))
("In Loop " + influencers_name)
names = influencers_name ::: names
}
for(n <- names) println("List element -> " + n)
Upvotes: 0
Reputation: 3250
The reason is, When you do names ::: List("anything") -> it does not add anything to names. Instead, it creates a new collection. For example,
scala> var names: List[String] = Nil
names: List[String] = List()
scala> names ::: List("mahesh")
res0: List[String] = List(mahesh)
You can achive that
scala> names ::: List("chand")
res1: List[String] = List(chand)
scala> res0 ::: List("chand")
res2: List[String] = List(mahesh, chand)
When I added "Mahesh" to it, it has created new collection naming res0. When I added again different string, here "chand" it has created another collection. But when I added "chand" to the created collection, it has concatenated to correct collection,
You can achive What you want to do,
scala> for(i <- List("a" ,"b" )){
| names = i :: names }
scala> names
res11: List[String] = List(b, a)
Upvotes: 0