Monday, August 3, 2009

Basic Collection Operations

In this example I show some common operations that can be performed on all collections. The examples use list but any Iterable can be used.
  1. scala>val list = List(1,2,3,4)
  2. list: List[Int] = List(1, 2, 3, 4)
  3. scala> list.mkString(",")
  4. res0: String = 1,2,3,4
  5. scala> list.mkString("(",",",")")
  6. res1: String = (1,2,3,4)
  7. scala> list.reduceLeft ( (next,cumulative) => cumulative + next )
  8. res2: Int = 10
  9. scala>for( e <- list ) println ( e ) 
  10. 1 2 3 4  
  11. scala>for( e <- list ) {      
  12.      | println ( e )      
  13.      | } 
  14. 1 2 3 4  
  15. scala>for( e <- list ) yield e+1 
  16. res5: List[Int] = List(2, 3, 4, 5)  
  17. scala>for ( e <- list; if( e % 2 == 0 ) ) yield e 
  18. res6: List[Int] = List(2, 4)

No comments:

Post a Comment