java—如何迭代scala中的每个状态?

bejyjqdl  于 2021-06-30  发布在  Java
关注(0)|答案(3)|浏览(214)

我尝试遍历每个状态,以检查arraylist是否至少有一个active和一个inactive状态。

var active = false;
var inactive = false;
for (item <- reasons.items) {
  if(item.status == "ACTIVE")
    active = true
  if(item.status == "INACTIVE")
    }
active must be (true)
inactive must be (true)

有没有更干净的方法?我试过这样的溪流,但运气不好

var active = false;      
var stream = reasons.items.toStream
        .forEach(item => if(item.status == "ACTIVE") {active = true})

注:原因保留项(共1项)。items包含可以像reasons.items.get(x)那样调用的单个项。

f2uvfpb9

f2uvfpb91#

干净的方法是

val active = reasons.items.exists(item => item.status == "ACTIVE")

或更短

val active = reasons.items.exists(_.status == "ACTIVE")

同样适用于 val inactive . 这确实存在两次遍历列表的问题(但是在找到合适的项时停止两次,这与代码中的情况不同)。

3xiyfsfu

3xiyfsfu2#

其他答案很好地解释了如何使用scala集合实现这一点。因为看起来您使用的是scalatest,所以我想补充一点,您也可以使用scalatest在元素上循环。
使用检查器中的循环样式语法:

forAtLeast(1, reasons.items) { item =>
  item.status must be ("ACTIVE")
}

forAtLeast(1, reasons.items) { item =>
  item.status must be ("INACTIVE")
}

请注意,检查器是与匹配器分开定义的,因此您必须 import org.scalatest.Inspectors._ 或者 extends … with org.scalatest.Inspectors 得到 forAtLeast 进入范围。
如果要避免检查器使用循环样式语法,可以将检查器速记语法与基于反射的语法一起使用 have 语法:

atLeast(1, reasons.items) must have ('status "ACTIVE")
atLeast(1, reasons.items) must have ('status "INACTIVE")

如果要避免使用基于反射的语法 have ,可以扩展 have 支持 status 直接财产:

def status(expectedValue: String) =
  new HavePropertyMatcher[Item, String] {
    def apply(item: Item) =
      HavePropertyMatchResult(
        item.status == expectedValue,
        "status",
        expectedValue,
        item.title
      )
  }

atLeast(1, reasons.items) must have (status "ACTIVE")
atLeast(1, reasons.items) must have (status "INACTIVE")

或者如果你愿意的话 be 结束 have ,你可以延长 be 添加支持的语法 active 以及 inactive :

class StatusMatcher(expectedValue: String) extends BeMatcher[Item] {
  def apply(left: Item) =
    MatchResult(
      left.status == expectedValue,
      left.toString + " did not have status " + expectedValue,
      left.toString + " had status " + expectedValue,
    )
}

val active = new StatusMatcher("ACTIVE")
val inactive = new statusMatcher("INACTIVE")

atLeast(1, reasons.items) must be (active)
atLeast(1, reasons.items) must be (inactive)

在这里的示例中,定义自己的匹配器只是为了在一个Assert中保存几个单词,这看起来有点愚蠢,但是如果您编写了数百个关于相同属性的测试,那么将Assert简化为一行并保持自然可读性就非常方便了。所以根据我的经验,如果在很多测试中重用它们,那么像这样定义自己的匹配器是有意义的。

a8jjtwal

a8jjtwal3#

对于“至少1”,您可以使用 existsitems 它检查给定的 predicate ,如果至少有一个项满足条件,则返回true。对于“活动”和“非活动”,您可以将两者结合起来 exists 需要使用&&&的低效方法。

reasons.items.exists(_.status.equals("ACTIVE")) && reasons.items.exists(_.status.equals("INACTIVE"))`

相关问题