I have a list of Custom objects which will be compared against rest of the objects in the same list.
My current approach: Currently i take one element from a the list using foreach loop,run another foreach loop to look through the list for elements that are similar to the taken object.
case class TestOb(name:String,pos:Vector[Int])
val lis:List[TestOb] = null
lis.foreach{i=>
val ref = i._2
lis.foreach{j=>
val current = j._2
//compare ref and current.
}
}
Is there any other efficient way to do this iteration in Scala within same list without having two foreach loops?
Have you tried using the for-loop?
for( a <- lis; b <- lis) {
// do stuff with a and b
}
For further convinience here an easy example to get an idea of the iteration going on behind the scenes:
scala> val list = 1 to 3
list: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3)
scala> for(a <- list; b <- list) println(a+" - "+b)
1 - 1
1 - 2
1 - 3
2 - 1
2 - 2
2 - 3
3 - 1
3 - 2
3 - 3
For what its worth, enzymes solution would be more in line with the functional style scala embraces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With