6

What is a neat way to hold pairs of strings which are not necessarily key-values (might have duplicate keys), for a small collection? List[List[String]] works obviously but looks dirty.

Cheers
Parsa

Eugene Yokota
  • 94,654
  • 45
  • 215
  • 319
parsa
  • 2,628
  • 3
  • 34
  • 44

2 Answers2

14

List[(String,String)] is the standard solution:

scala> List(("foo","bar"), ("foo","baz"))
res1: List[(java.lang.String, java.lang.String)] = List((foo,bar), (foo,baz))
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • 3
    Exactly! The nice thing about tuples is that equality, pattern matching, etc. works as one would expect. `("foo", "bar") == ("foo", "bar")` returns `true`, for example. – soc Oct 17 '10 at 12:27
  • 3
    You also get lexicographic ordering of pairs, which is an extremely nice freebie. – Dave Griffith Oct 17 '10 at 13:53
  • 2
    I came across this nice tuple trick yesterday: http://goo.gl/MT6J. It makes a good use of the fact that all the tuple classes have instances of `Ordering` trait defined for them. – missingfaktor Oct 17 '10 at 15:30
11

Tuples are the ideal data structure to represent pairs.

So use a list of (String, String) tuples.

sepp2k
  • 363,768
  • 54
  • 674
  • 675