Kotlin list comparisons

Praveen Alex Mathew
1 min readFeb 19, 2019

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Praveen Alex Mathew
Praveen Alex Mathew

Written by Praveen Alex Mathew

Software Developer. Masters in Computer Science @Arizona State University. https://praveenmathew92.github.io/

Responses (2)

Write a response