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

ListScalaScala Java-Interop

List Problem Overview


I have this Scala method with below error. Cannot convert into a Scala list.

 def findAllQuestion():List[Question]={
   questionDao.getAllQuestions()
 } 

type mismatch; found : java.util.List[com.aitrich.learnware.model.domain.entity.Question] required: scala.collection.immutable.List[com.aitrich.learnware.model.domain.entity.Question]

List Solutions


Solution 1 - List

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

import scala.collection.JavaConverters._

def findAllQuestion():List[Question] = {
  questionDao.getAllQuestions().asScala.toList
}

Solution 2 - List

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}

Solution 3 - List

def findAllStudentTest(): List[StudentTest] = { 
  studentTestDao.getAllStudentTests().asScala.toList
} 

Solution 4 - List

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)

Solution 5 - List

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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionboycod3View Question on Stackoverflow
Solution 1 - ListFynnView Answer on Stackoverflow
Solution 2 - ListNeilView Answer on Stackoverflow
Solution 3 - Listboycod3View Answer on Stackoverflow
Solution 4 - ListXavier GuihotView Answer on Stackoverflow
Solution 5 - ListRaymond ChenonView Answer on Stackoverflow