如何检查列表是否包含所有相同的值? [英] How to check if list contains all the same values?

查看:39
本文介绍了如何检查列表是否包含所有相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个List[<DataType>]作为输入.我想检查列表是否包含所有相同的值(不是数据类型).

I have a List[<DataType>] as input. I want to check if the list contains all the same values(not datatype).

Scala中有内置的方法或直观的方法来执行此操作,而不是遍历列表和检查.

Is there inbuilt method or intuitive way in Scala to do this instead of iterating over list and checking.

推荐答案

这将在第一个非等于元素上终止.元素类型必须支持类似==!=的比较器.

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

这篇关于如何检查列表是否包含所有相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆