Reputation: 1389
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?
Upvotes: 2
Views: 11073
Reputation: 433
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.
Upvotes: 7
Reputation: 20415
An approach to compare each element in a collection against the rest and to collect those that are similar (here identical by using ==
in collect
). In order to illustrate the case consider
case class C(i:Int)
and a collection where C(1)
has a similar
item (equality here),
val xs = Array( C(1),C(2),C(3),C(1),C(4) )
Hence we combine each two items, compare them and collect those similar,
xs.combinations(2).collect { case Array(a,b) if a == b => a }.toArray
Array(C(1))
Note combinations
delivers an iterator which is consumed (iterated over) by collect
. Also, replace ==
in collect
with a dissimilarity function for comparing items to decide which are similar enough.
Upvotes: 3