forEach is a sideEffecting function and will iterate over the entire Map. The closure passed into forEach cannot be considered the same an an imperative while loop. Scala and functional programming are declarative. So all you are doing is declaring some function to run on each Tuple of the map.
u=>if (u.getKey()=="parameter") return true
This is a function declared that will be executed over every element of the Map (maps can be traversed like lists). The lambda also is running in a different context than isParameterSet. I think the equivalent code segment to your scala code is:
def checkParameter(parameter: String, iterator: Iterator): Unit = {
if (iterator.next().getKey() == parameter)
return true
}
def isParameterSet(parameter: String): Boolean = {
//java based
val iterator = newConfig.entrySet().iterator()
while (iterator.hasNext()) {
checkParameter(parameter, iterator)
}
return false
}
So here the return true does not affect isParameterSet since its in a different context.
Look at how closures and Lambda expressions work. The idea is not Scala specific so you can learn the concepts in something you are more familiar with (Java 8 has closures now). Learning this stuff on top of a unfamiliar language can be frustrating.
Below is some code to deal with how to check if your parameter is set. I made some assumptions here where a null value means a parameter is not set. I also tried to comment my intentions for you. Let me know if its not clear
package parameter_set
// Its usually considered ideal to keep all imports at the top of the code just like in Java
import java.util
import scala.collection.JavaConverters._
object ParameterSet extends App {
val javaConfig: util.Map[String, String] = new util.HashMap[String, String]()
javaConfig.put("param1", "value1")
javaConfig.put("param2", "value2")
javaConfig.put("param3", "value3")
javaConfig.put("param4", null)
// The Option will make sense in a second
val newConfig: Map[String, String] = javaConfig
// converts it to a mutable map
.asScala
// converts it to an immutable map
.toMap
// I am a bit paranoid since this was a Java map and I need to make sure all null values are handled as Option
.mapValues(value => Option(value))
// This resolves a known issue since mapValues creates a view over the underlying Map (http://stackoverflow.com/questions/14882642/scala-why-mapvalues-produces-a-view-and-is-there-any-stable-alternatives)
.view
.force
// Now we need to only take the key -> values
.collect {
case (key, Some(value)) => key -> value
}
def isParameterSet(parameter: String): Boolean = newConfig.exists(parameters => parameters._1 == parameter)
println(isParameterSet("param2")) //true
println(isParameterSet("param7")) //false
println(isParameterSet("param4")) //false
}