0

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

2
  • Could you print JavaList and scalaArray prior to filtering? And possibly JavaList.toArray? Thanks. Commented Aug 27, 2020 at 10:31
  • 1
    By the way, it's not necessary to create a variable named res, then check if it's empty in an if statement, and return true or false manually. You could just return res.isEmpty or write the whole thing out in one line Commented Aug 27, 2020 at 13:53

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.