How to convert a java.util.List to a Scala list

情到浓时终转凉″ 提交于 2019-11-27 10:46:13
Neil
import scala.collection.JavaConversions._

will do implicit conversion for you; e.g.:

var list = new java.util.ArrayList[Int](1,2,3)
list.foreach{println}

You can simply convert the List using Scala's JavaConverters:

import scala.collection.JavaConverters._

def findAllQuestion():List[Question] = {
  questionDao.getAllQuestions().asScala
}
boycod3
def findAllStudentTest(): List[StudentTest] = { 
  studentTestDao.getAllStudentTests().asScala.toList
} 

Import JavaConverters , the response of @fynn was missing toList

import scala.collection.JavaConverters._

def findAllQuestion():List[Question] = {
  //           java.util.List -> Buffer -> List
  questionDao.getAllQuestions().asScala.toList
}

Starting Scala 2.13, the package scala.collection.JavaConverters is marked as deprecated in favor of scala.jdk.CollectionConverters:

import scala.jdk.CollectionConverters._

// val javaList: java.util.List[Int] = java.util.Arrays.asList(1, 2, 3)
javaList.asScala.toList
// List[Int] = List(1, 2, 3)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!