| 1. |
Explain The Main Difference Between List And Stream In Scala Collection Api? How Do We Prove That Difference? When Do We Choose Stream? |
|
Answer» In Scala, both List and Stream are from Collection API and works almost similar. Both are Immutable COLLECTIONS. However, there is one main difference between List and Stream in Scala Collection API: That is List elements are evaluated Eagerly and Stream elements are evaluated Lazily that means when we access them. scala> VAR list1 = List(1,2,3,4) Here we can observe that all List elements evaluated at the time of creating List object. However, if we do same thing on Stream, we cannot SEE all elements. We can see only first evaluated element and remaining elements are evaluated lazily as shown below: scala> var s1 = Stream(1,2,3,4) When we want LAZY collection to evaluate elements only when we access them then it’s better to use Stream. In Scala, both List and Stream are from Collection API and works almost similar. Both are Immutable collections. However, there is one main difference between List and Stream in Scala Collection API: That is List elements are evaluated Eagerly and Stream elements are evaluated Lazily that means when we access them. scala> var list1 = List(1,2,3,4) Here we can observe that all List elements evaluated at the time of creating List object. However, if we do same thing on Stream, we cannot see all elements. We can see only first evaluated element and remaining elements are evaluated lazily as shown below: scala> var s1 = Stream(1,2,3,4) When we want Lazy collection to evaluate elements only when we access them then it’s better to use Stream. |
|