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 extract A only, without B, as I need to compare A with some other variable. So the final result should be 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 }
// equivalent to:
val myKeys = collection.keySet.map(tup => tup._1)
// equivalent to: */
val myKeys = myCollection.keySet.map(_._1)
println(myKeys)
Output:
Set(one, two, three)