lucki
lucki

Reputation: 3

How to see if an Array contains a value from another Java List in Scala?

I have 1 Scala Array containing Strings and 1 Java Util List containing Strings. I want to check if value of one Array is in the other List, and set a flag accordingly.

def getFlag(JavaList, scalaArray): Boolean = {
  val res = JavaList.toArray.filter(x => scalaArray.contains(x))

  if (res.isEmpty)
    false
  else 
    true
}

the contains doesn't seem to be working. It always shows the size as 0 even when there should be a matching string and I'm not sure why.

How would I fix this or are there any other better methods of doing this? I am trying to get more familiar with Scala any help is appreciated thank you

Upvotes: 0

Views: 128

Answers (1)

I would use exists and I would transform the Array into a Set to speed up the check.

// This one for 2.13+
import scala.jdk.CollectionConverters._
// This one for 2.12-
import scala.collection.JavaConverters._

def getFlag(javaList: java.util.List[String], scalaArray: Array[String]): Boolean = {
  val values = scalaArray.toSet
  javaList.asScala.exists(values.contains)
}

If you get a false, then there are some errors in the strings, maybe try converting them to lower case or checking if there are invisible characters in there.


I am trying to get more familiar with Scala any help is appreciated thank you

My best advice would be try to stay away from Java collections and from plain Arrays. Instead, use collections from the Scala library like: List, Vector, ArraySeq, Set, Map, etc.

Upvotes: 5

Related Questions