Freewind
Freewind

Reputation: 198188

How to check if a map contain a empty string value in scala?

I have a newbie question.

We can use contains to check if a map contain a specified key, as:

val map = Map("a"->"1", "b"->"")
map.contains("a")

But now, I want to check if the map contains an empty string, is there any method to use?

Upvotes: 4

Views: 6074

Answers (3)

Antonin Brettsnajdr
Antonin Brettsnajdr

Reputation: 4143

Or you can just write:

map contains ""

Upvotes: -1

Rex Kerr
Rex Kerr

Reputation: 167871

Try

map.values.exists(_ == "")

Edit: I think the above is the clearest, but I can't resist showing two others.

map.exists(_._2 == "")

is more compact, but you have to remember that _2 is the value when you iterate through a map.

map.values.exists(""==)

is an alternative form of the original, where instead of explicitly comparing the argument with _ == "", you supply an equality function "".equals _ or ""== for short. (Two ways of looking at the same thing--is it the empty string supplying its equals method for testing, or is it your closure testing the elements against the empty string? I think the latter (the original) is considerably clearer.)

Upvotes: 12

Submonoid
Submonoid

Reputation: 2829

You can do:

map.values.toSet.contains("")

or:

map find { case (a,b) => b == "" } isDefined

Upvotes: 0

Related Questions