Can we check if the elements in a list are vaild without looping over them?

Imagine an application taking a list of cities as input. How does it check whether the input list is valid or not.

If the application is in Java or Kotlin, mostly the list of valid cities would be stored as an enum as below.

enum class City {
DELHI,
MUMBAI,
CHENNAI,
BANGALORE
}

And the input list would be

val inputCities: List<String> = listOf("MUMBAI", "CHENNAI", "DUBAI")

The rudimentary approach would be to iterate over the inputCities and check for each if it is present in the enum till all cities are done or till a city not present in the enum is encountered.

fun isValid(inputCities: List<String>): boolean {
val validCities = City.values()
return inputCities.all{ inputCity ->
validCities.contains(inputCity)
}
}

But, can we do better.

Enter the minus function

The minus function internally converts the list to a set making the computation faster while not compromising on the readbility.

fun isValid(inputCities: List<String>): boolean {
val validCities = City.values()
val invalidInputCities = inputCities.minus(validCities)
return invalidInputCities.none()
}

This makes the function more readable and we also get rid of the for loop.

Note: This solution assumes that the input list contains no duplicate entries.

Masters in Computer Science @Arizona State University, Ex-ThoughtWorks