在Scala中将List[List[Long]]
转换为List[List[Int]]
的最佳方法是什么?
例如,给定以下类型为List[List[Long]]
的列表
val l: List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
如何将其转换为List[List[Int]]
?
答案 0 :(得分:5)
像这样尝试l.map(_.map(_.toInt))
val l: List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
l.map(_.map(_.toInt))
应该给的
res2: List[List[Int]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
答案 1 :(得分:4)
您还可以为此使用cats
lib并组成List
仿函数
import cats.Functor
import cats.implicits._
import cats.data._
val l: List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
Functor[List].compose[List].map(l)(_.toInt)
//or
Nested(l).map(_.toInt).value
和另一种纯scala方法(虽然不是很安全)
val res:List[List[Int]] = l.asInstanceOf[List[List[Int]]]
答案 2 :(得分:3)
仅在完全确定不会溢出 Int 的情况下。
val l1: List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
val l2: List[List[Int]] = l1.map(list => list.map(long => long.toInt))
(基本上,每次您要将列表转换为另一个列表时,请使用map
)。
答案 3 :(得分:2)
可以通过使用map
函数对集合进行简单的转换来实现。
map
通过对列表中的每个元素应用函数来工作。在您的情况下,有嵌套列表。因此您需要两次应用map
函数,如下面的示例所示。
val x : List[List[Long]] = List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
println(x)
val y :List[List[Int]]= x.map(a => a.map(_.toInt))
println(y)
输出:
List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))
List(List(11, 10, 11, 10, 11), List(8, 19, 24, 0, 2))