scala 检查集合包含多少个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20305064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking how many elements a set contains
提问by user2947615
I need to write a function that returns true if a set (this set is the output of another function) contains 1 element and otherwise it leaves the set as it is.
我需要编写一个函数,如果一个集合(这个集合是另一个函数的输出)包含 1 个元素,则该函数返回 true,否则它保持原样。
For example:
例如:
Set(1) returns a specific result and Set(2,4) returns the set as it is.
Set(1) 返回一个特定的结果,而 Set(2,4) 按原样返回集合。
How can I check how many elements a set contains?
如何检查集合包含多少个元素?
回答by DNA
You just need the sizemethod on a Set:
您只需要sizeSet 上的方法:
scala> Set(1).size
res0: Int = 1
scala> Set(1,2).size
res1: Int = 2
See also the documentation for Set.
Let's say your other function is called getSet. So all you need to do is call it, then check the size of the resulting Set, and return a value depending on that size. For example, I shall assume that if the set's size is 1, we need to return a special value (a Set containing the value 99) - but just replace this with whatever specific result you actually need to return.
假设您的另一个函数被调用getSet。所以你需要做的就是调用它,然后检查结果的大小Set,并根据该大小返回一个值。例如,我假设如果集合的大小为 1,我们需要返回一个特殊值(一个包含值 99 的集合)——但只需将它替换为您实际需要返回的任何特定结果。
def mySet = {
val myset = getSet()
if (myset.size == 1) Set(99) // return special value
else myset // return original set unchanged
}

