I have a Scala map collection that looks something like this:
var collection = Map((A,B)) -> 1)
The key is (A,B) and the value is 1.
My question: If I use collection.head._1
, the result is (A,B) which is correct. But I want to only extract key 'A' and not the key 'B'/set as I have to compare 'A' with some other variable.
So the final result should be the only key 'A' stored in a different variable.
I tried to use collection.head._1(0)
which results in error
Any does not take parameters
CodePudding user response:
You can try:
val collection = Map(("A","B") -> 1)
collection.map{ case ((a, b),v) => a -> v}
CodePudding user response:
You need to use keySet
to get a Set
of Tuple2
and then map
into only the first element of each:
val collection =
Map(
("one", "elephant") -> 1,
("two", "elephants") -> 2,
("three", "elephants") -> 3
)
val myKeys = collection.keySet.map { case (x, _) => x }
println(myKeys)
Output:
Set(one, two, three)