scala - 如何匹配列表元素
问题描述
我想匹配列表是否包含某个元素,并根据不同的元素返回不同的结果。我用if else写的,现在想用match case写,但是我对match case不是很熟悉,谁能帮我写case匹配的方式,谢谢
下面是if else的代码
val sten=List(sort_view.head._1,sort_view(1)._1)
if(sten.contains("Positive")) println("Positive")
else if (sten.contains("Neutral")) println("Neutral")
else if (sten.contains("Negative")) println("Negative")
else if (sten.contains("Verynegative")) println("Verynegative")
解决方案
您可以过滤并获得第一个结果:
List("Positive", "Neutral", "Negative", "Verynegative")
.filter(sten.contains)
.headOption
.foreach(println)
在这种情况下,它比模式匹配更容易和更干净。
推荐阅读
- java - 如何读取 Firestore 子集合并将其传递给 FirestoreRecyclerOptions
- c++ - 相同的比较函数为 C++ 中的排序和优先级队列提供不同的输出
- javascript - 在 JavaScript 中打破 for 循环
- mysql - 有没有办法在列和整个表之间创建关系?
- php - 数字格式 PHP
- html - HTML 无意义元素,纯粹用于用 ID 包装内容
- php - 将变量变量传递给闭包会引发解析错误?
- java - Hibernate 无法创建具有@ManyToOne 关系的表
- ios - iOS:用户能否读取存储在 Core Data 中的数据
- mysql - laravel php artisan 迁移问题