Vishwas
Vishwas

Reputation: 7067

How match elements from two lists in scala?

I have two list as given following-

val a = List((HarddiskVolume1,31,1), (C:,46552070,433057), (E:,5435,1728), (_Total,46557536,434786))
val b =  List(C:, E:)

I wants output as following: o/p (C:,46552070,433057), (E:,5435,1728)

How do I get desired output using scala??

Upvotes: 0

Views: 3563

Answers (3)

user-asterix
user-asterix

Reputation: 936

Answering @Yogesh in case the data exists as a list within a list:

val aa =List(List(("HarddiskVolume1",31,1), ("C:",46552070,433057), ("E:",5435,1728), ("_Total",46557536,434786)),
             List(("HarddiskVolume1",31,1), ("C:",46552070,433057), ("E:",5435,1728), ("_Total",46557536,434786))
            )
val b =  List("C:", "E:")

aa.map(l => l.filter(x => b.exists(_== x._1))) 

Similar to Shyamendra but using exists operator on a list.

Upvotes: 0

elm
elm

Reputation: 20405

Using collect like this,

val keys = b.toSet
a collect { case z@(x,_,_) if keys(x) => z }

Update

Other similar approaches include

for ( z <- a if keys(z._1) ) yield z

a collect { case z if keys(z._1) => z }

( a partition ( z =>  keys(z._1) ) )._1

Upvotes: 2

Shyamendra Solanki
Shyamendra Solanki

Reputation: 8851

val a = List(("HarddiskVolume1",31,1), ("C:",46552070,433057), ("E:",5435,1728), ("_Total",46557536,434786))     

val b =  List("C:", "E:")

a.filter(x => b.contains(x._1))  // if b is large, consider making it a set.
// res0: List[(String, Int, Int)] = List((C:,46552070,433057), (E:,5435,1728))

Upvotes: 4

Related Questions