scala 如何检查列表是否包含所有相同的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/41478133/
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
How to check if list contains all the same values?
提问by Deepak Punjabi
I have a List[<DataType>]as input. I want to check if the list contains all the same values(not datatype). 
我有一个List[<DataType>]作为输入。我想检查列表是否包含所有相同的值(不是数据类型)。
Is there inbuilt method or intuitive way in Scala to do this instead of iterating over list and checking.
Scala 中是否有内置方法或直观的方法来执行此操作,而不是迭代列表和检查。
回答by jwvh
This will terminate on the first non-equals element. The element type has to support a comparator like ==or !=.
这将在第一个不等于元素处终止。元素类型必须支持像==或这样的比较器!=。
lst.forall(_ == lst.head)  // true  if empty or all the same
lst.exists(_ != lst.head)  // false if empty or all the same
回答by AbuNassar
I just had to do this for an unrelated problem, so to improve on the above ever so slightly: lst.tail.forall(_ == lst.head). This avoids checking that the head of the list equals itself, which you already know is true.
我不得不为一个不相关的问题,做到这一点,所以要改善上述非常轻微:lst.tail.forall(_ == lst.head)。这避免了检查列表的头部是否等于自身,您已经知道这是真的。
回答by awwsmm
One (inefficient but elegant) way is
一种(低效但优雅的)方式是
List(1, 2, 2, 1, 1).distinct.length == 1 // returns false
List(1, 1, 1, 1, 1).distinct.length == 1 // returns true
List().distinct.length == 1 // empty list returns false
Note that they must be of the same type
请注意,它们必须属于同一类型
List(4, 4.0, "4").distinct.length == 1 // returns false

