28

There is a nice flowchart (taken from here) for choosing a particular container in C++:

container-flowchart

Is there something similar for the Scala collections? I'm still somewhat overwhelmed with the options.

Community
  • 1
  • 1
fredoverflow
  • 256,549
  • 94
  • 388
  • 662

1 Answers1

62

I am not aware of such flowcharts for Scala, but I guess one would be useful. I made one for you -- larger picture here.

Note that there is some added complexity, since Scala has more collections and there is both the mutable and the immutable package. Where possible, I added both alternatives to the rectangle.

I tried to follow the C++ STL flow diagram as much as possible, but I thought that the lower left part was complicating things a bit too much, so I changed the flow there slightly.

EDIT: fixed some typos.

EDIT: As Travis, suggested, note that in a majority of situations, you only need to pick between a Map, Set, List, ArrayBuffer or a Vector.

  • if you need key-value lookup, use a Map
  • if you need to check for presence of elements, use a Set
  • if you need to store elements and traverse them, use a List or an ArrayBuffer
  • if you don't need a persistent collection, but random access is really important, use ArrayBuffer
  • if you need relatively fast random access and persistent sequences, use Vector

If that does not help and you have a more exotic use-case, use this chart.

enter image description here

axel22
  • 32,045
  • 9
  • 125
  • 137
  • 1
    That's a rather nice flowchart. What did you use to make it? – haneefmubarak Jun 28 '14 at 16:02
  • The CorelDRAW application. It's pretty nice to use for vector graphics. – axel22 Jun 28 '14 at 16:28
  • 2
    The vast majority of the time in idiomatic Scala you'll be using `Map`, `Set`, `List`, and `Vector` (or `Seq` and `IndexedSeq` for the last two, according to some people). This is a handy chart, but it may make the situation seem even more confusing than it really is. – Travis Brown Jun 28 '14 at 17:43
  • That's a good point. I think I'll edit my answer to point that out. – axel22 Jun 28 '14 at 17:45
  • Nice chart, but immutable.HashMap is located on both sides of question "Order is important". That is a bit confusing. – Darko Cerdic Jun 30 '14 at 09:44
  • If insertion order is not important, one can use `immutable.HashMap`. If insertion order is important, `immutable.HashMap` can be used together with `immutable.TreeMap` to track insertion order - see http://stackoverflow.com/questions/9313866/immutable-scala-map-implementation-that-preserves-insertion-order. One could also use `ListMap` for that, but with `O(n)` lookup. – axel22 Jun 30 '14 at 11:31
  • @axel22 care to update this excellent flowchart for Scala 2.13? – Mike Slinn Jun 18 '19 at 01:46