Aparna
Aparna

Reputation: 465

What is better? foreach and update map vs use list.map

Which of the following is better and why?

Case 1:

Map[String, String] result = Map.empty[String,String]
inputList.foreach(i => result += (i -> "hi") )

Case 2:

inputList.map(i => (i , "hi")).toMap

Upvotes: 0

Views: 62

Answers (2)

Tim
Tim

Reputation: 27421

Case 2

This is the functional way to implement it and is clearer about what the code is actually doing. If you are concerned about performance then using a view gives pretty much the same code as case 1 but, again, is clearer.

And to state the obvious, if case 2 is not possible then use case 1.

Upvotes: 2

Mateusz Kubuszok
Mateusz Kubuszok

Reputation: 27595

Which one is best is really a matter of use case. If this was a pipeline where I would pass/transform data and turning List[String] to Map[String, String] was just part of it, I would prefer to use .map with .toMap as it makes reading, maintenance and understanding easier

something.
  .map(someMap)
  .filter(condition)
  .map(i => i -> "hi")
  .toMap
  .mapValues(something)
  ...

However, if this was used in some part of a framework that instead of Future or IOs used callbacks, and the only way for me to get the result would be appending it to something, .foreach would be one of options I would consider

val mutableMap = mutable.Map.empty[String,String]
someSadLibrary.onComplete { result =>
  result.foreach { value =>
    mutableMap += ...
  }
}

If the code was on a really hot path I would probably take some immutable input, then use mutable structures to build result and finally return immutable result. That would also require .foreach and mutation (I almost never see a reason to do it in my code, more like in libraries internals).

Long story short, .map(...).toMap would be almost always better, but in some specific situations where it wouldn't be an option I would consider mutation.

Upvotes: 2

Related Questions