Check a condition within a foreach in scala

Viewed 9887

Is there a way to check a condition within a foreach loop in scala. The example is that I want to go through an array of integers and do some arbitrary math on the positive numbers.

val arr = Array(-1,2,3,0,-7,4) //The array

//What I want to do but doesn't work

arr.foreach{if(/*This condition is true*/)
              {/*Do some math and print the answer*/}}

//Expected answer for division by six is 0.333333333 \n 0.5 \n 0.666666667
//Which is 2/6, 3/6 and 4/6 respectively as they appear in the array

I know how to do it with a normal for loop and if statement but I want to use this because I want to get away from java.

Thanks

6 Answers
var list: ListSet[Int] = ListSet(-1, -5, -3, 8, 7, 9, 4, 6, 2, 1, 0)

list.filter(p => p > 5).foreach(f => {
  print(f + " ")
})

Output : 8 7 9 6 
Related