Skip to content

Commit 4c01ae7

Browse files
committed
Various operations in scala
1 parent 6bfcd8e commit 4c01ae7

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
Various operations in scala using scala interpreter
2+
3+
4+
//This will partition the collection
5+
scala> (1 to 8).partition(x => x%2 != 0)
6+
res2: (scala.collection.immutable.IndexedSeq[Int], scala.collection.immutable.IndexedSeq[Int]) = (Vector(1, 3, 5, 7),Vector(2, 4, 6, 8))
7+
8+
scala> List(1,2,3,4,5,6,7,8).partition(x => x%2 != 0)
9+
res3: (List[Int], List[Int]) = (List(1, 3, 5, 7),List(2, 4, 6, 8))
10+
11+
//Group By Operation on a list. groupBy returns a map with key as function evaluation on each element in list and value as List of element
12+
scala> List("Red", "Orange", "Green", "Purple", "Pink").groupBy(x => x.head)
13+
res4: scala.collection.immutable.Map[Char,List[String]] = Map(P -> List(Purple, Pink), G -> List(Green), R -> List(Red), O -> List(Orange))
14+
15+
//Take operation on collection.
16+
//This will take first 10 elements in collection
17+
scala> (1 to 100).take(10)
18+
res5: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
19+
20+
//takeRight will take last 10 elements in collection
21+
scala> (1 to 100).takeRight(10)
22+
res6: scala.collection.immutable.Range = Range(91, 92, 93, 94, 95, 96, 97, 98, 99, 100)
23+
24+
//takeWhile will take all elements which satisfy a predicate
25+
scala> (1 to 100).takeWhile(x => x < 40)
26+
res7: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39)
27+
28+
//distinct operation on a collection
29+
scala> List(1,2,3,4,4,3,2,1).distinct
30+
res8: List[Int] = List(1, 2, 3, 4)
31+
32+
//Empty List of String
33+
scala> List.empty[String]
34+
res9: List[String] = List()
35+
36+
//Empty List of Int
37+
scala> List.empty[Int]
38+
res10: List[Int] = List()
39+
40+
//Initializing a list of 10 elements with a value
41+
scala> List.fill(10){
42+
| val x = 10
43+
| val y = 20
44+
| x + y+ 30
45+
| }
46+
res11: List[Int] = List(60, 60, 60, 60, 60, 60, 60, 60, 60, 60)

0 commit comments

Comments
 (0)