ps0604
ps0604

Reputation: 1071

Finding array with empty elements

I have the following structure:

val s1 = Seq(1,2,3,4,5)
val s2 = Seq()
val s3 = Seq(6,7,8,9)
val seq = Seq(s1,s2,s3)

What I need is to validate that all the sequences in seq have at least one element. I tried to accomplish this with filter, but couldn't, any ideas?

Upvotes: 0

Views: 69

Answers (4)

Gabriele Petronella
Gabriele Petronella

Reputation: 108101

This finds all the sequences with at least one element

seq.filterNot(_.isEmpty)

while this checks that all sequences have at least one element

seq.forAll(!_.isEmpty)

or

!seq.exists(_.isEmpty)

Upvotes: 1

Raman Mishra
Raman Mishra

Reputation: 2686

This should also work.

seq.filter(_.nonEmpty)

Upvotes: 0

Xavier Guihot
Xavier Guihot

Reputation: 61666

You're probably looking for the forall function:

seq.forall(!_.isEmpty)

which translates into: Are all sequences in seq non-empty? and thus returns false with your example since s2 is empty.

Upvotes: 1

Manoj Kumar Dhakad
Manoj Kumar Dhakad

Reputation: 1892

You can use below line of code.

val distinct=seq.filter(_.length>0)

Upvotes: 1

Related Questions