Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at a simple program to filter positive numbers from a List of integers in Scala.
We can achieve this by applying filter method on the input list or using a for loop. Lets’ look at the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.clearurdoubt.filter object FilterPositiveInts extends App { // define a function to filter positive integers def filterPositiveInts(numbers: List[Int]) = { for(n <- numbers if n > 0) yield n } val nums = List(1, -1, 2, -2, 3) println("Input list: " + nums) val filtered = filterPositiveInts(nums) // calling our function to filter positive integers println("Filtered using for loop: " + filtered) println("Filtered using filter function: " + nums.filter(_ > 0)) // Simple way to apply filter } |
Output:
Happy Learning.
Please leave a reply in case of any queries.