Check how many items a set contains

I need to write a function that returns true if the set (this set is the output of another function) contains 1 element, and otherwise it leaves the set as it is.

For example:

Set (1) returns a specific result, and Set (2,4) returns a set as it is.

How to check how many elements a set contains?

+7
set scala boolean elements
source share
1 answer

You just need the size method in Set:

 scala> Set(1).size res0: Int = 1 scala> Set(1,2).size res1: Int = 2 

See also installation documentation.

Let's say your other function is called getSet . So, all you have to do is call it and then check the size of the resulting Set and return a value depending on that size. For example, I assume that if the set size is 1, we need to return a special value (a set containing a value of 99), but just replace it with some specific result that you really need to return.

 def mySet = { val myset = getSet() if (myset.size == 1) Set(99) // return special value else myset // return original set unchanged } 
+9
source share

All Articles