Filter a list in Scala

This is how to get a sublist in Scala and very similar to the new Streams API in Java.

The idea is you have a list and only want certain members of that list.

In this example I only want values in it above a certain threshold. My simple boolean condition – x > THRESHOLD is used to work out whether values go in my new list.

Here is the code:

object AddToAnotherList extends App {
  
  val THRESHOLD = 4
  val list1 = List(1,2,3,4,5,6,7)
  
  val validValues = list1.filter { x => x > THRESHOLD }
  
  println(s"Valid values = $validValues")
}

And the output:

Valid values = List(5, 6, 7)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s