Pyd
Pyd

Reputation: 6159

Key Value pair filter in an Array[Int,Int]

In an Array of Integers index: Array[(Int, Int)]

index = {(1,4),(2,5),(5,2)}

How to get the value of corresponding key like 1 -> 4 using filter function in scala

Upvotes: 1

Views: 853

Answers (2)

Rjk
Rjk

Reputation: 1474

Since its an Array of tuples you can get the values using _1 and _2.

index.filter(x => x._1 == 1).map(x => println(x._2))

Upvotes: 3

Nyavro
Nyavro

Reputation: 8866

Basically filtering Array of pairs by first item of pair looks like:

index.filter {case (k,v) => k==1} 

The result of this operation is Array of items matching the criteria. It is not clear from the question what if the index contains several items with key==1? So probably you are looking for find method:

index.find {case (k,v) => k==1} 

which returns Option of matching (key, value)

Upvotes: 3

Related Questions