[scala] range와 함수 내용을 넣은 Map 만들기- 예제
1부터 28까지의 숫자를 특정 함수에 넣고 그 값을 Map으로 리턴하고 싶다고 한다면. 다음과 같을 것이다.
scala> def multiply(num: Int): Int = { num *2 }
multiply: (num: Int)Int
scala> (1 to 28).map { i => (i, multiply(i)) }.toMap
res23: scala.collection.immutable.Map[Int,Int] = Map(5 -> 10, 10 -> 20, 24 -> 48, 25 -> 50, 14 -> 28, 20 -> 40, 1 -> 2, 6 -> 12, 28 -> 56, 21 -> 42, 9 -> 18, 13 -> 26, 2 -> 4, 17 -> 34, 22 -> 44, 27 -> 54, 12 -> 24, 7 -> 14, 3 -> 6, 18 -> 36, 16 -> 32, 11 -> 22, 26 -> 52, 23 -> 46, 8 -> 16, 19 -> 38, 4 -> 8, 15 -> 30)
키로 정렬하려면 TreeMap을 활용하면 깔끔히 정렬된다.
scala> val sortedMap = scala.collection.immutable.TreeMap(map.toSeq:_*)
sortedMap: scala.collection.immutable.TreeMap[Int,Int] = Map(1 -> 2, 2 -> 4, 3 -> 6, 4 -> 8, 5 -> 10, 6 -> 12, 7 -> 14, 8 -> 16, 9 -> 18, 10 -> 20, 11 -> 22, 12 -> 24, 13 -> 26, 14 -> 28, 15 -> 30, 16 -> 32, 17 -> 34, 18 -> 36, 19 -> 38, 20 -> 40, 21 -> 42, 22 -> 44, 23 -> 46, 24 -> 48, 25 -> 50, 26 -> 52, 27 -> 54, 28 -> 56)
예쁘게 출력하려면 mkString을 사용한다.
scala> sortedMap.mkString("\n")
res28: String =
1 -> 2
2 -> 4
3 -> 6
4 -> 8
5 -> 10
6 -> 12
7 -> 14
8 -> 16
9 -> 18
10 -> 20
11 -> 22
12 -> 24
13 -> 26
14 -> 28
15 -> 30
16 -> 32
17 -> 34
18 -> 36
19 -> 38
20 -> 40
21 -> 42
22 -> 44
23 -> 46
24 -> 48
25 -> 50
26 -> 52
27 -> 54
28 -> 56
참고로 주의할 점은 (1 to 28) 과 Collection(1 to 28)은 다르다..
scala> (1 to 28)
res24: scala.collection.immutable.Range.Inclusive = 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)
scala> List(1 to 28)
res25: List[scala.collection.immutable.Range.Inclusive] = List(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))