ac_nook
ac_nook

Reputation: 325

Scala: Finding unique value in a list of tuples

I have a list of tuples in Scala:

("BLUE", 2, 4)
("RED", 2, 29)
("GREEN", 29, 0)
("RED", 18, 2)

This list is quite long. I'm looking for an efficient list operation that would give me a list of unique colors (the first string in the tuple). In other words, I'm looking for this:

List("RED", "BLUE", "GREEN")

Order doesn't really matter to me. I know that this can be accomplished iteratively, but I'm looking to learn functional programming and I'm not sure how to do this with an operation.

Thank you!

Upvotes: 0

Views: 422

Answers (2)

jwvh
jwvh

Reputation: 51271

If it's a long List, as you say, then you'll want to traverse it only once.

tups.foldLeft(Set[String]())(_+_._1).toList

Upvotes: 1

Tanjin
Tanjin

Reputation: 2452

How about:

tupleList.map(_._1).distinct

Upvotes: 1

Related Questions