{"id":4332,"date":"2016-06-04T01:39:42","date_gmt":"2016-06-04T01:39:42","guid":{"rendered":"http:\/\/www.garysieling.com\/blog\/?p=4332"},"modified":"2016-06-04T01:39:42","modified_gmt":"2016-06-04T01:39:42","slug":"scala-filter-nones-listoption","status":"publish","type":"post","link":"https:\/\/www.garysieling.com\/blog\/scala-filter-nones-listoption\/","title":{"rendered":"Scala: Filter None&#8217;s from a List[Option]"},"content":{"rendered":"<p>The simplest way to remove all the Options (both the Some wrappers and Nones) from a list is to flatten it:<\/p>\n<pre lang=\"scala\">\nList(\n  Option(\"a\"), \n  Option(\"b\"), \n  None\n).flatten\n\nres39: List[String] = List(a, b)\n<\/pre>\n<p>You can achieve the same effect by using flatMap, which will allow you to modify the results if you need to (e.g. to change the type or modify the values):<\/p>\n<pre lang=\"scala\">\nList(\n  Option(\"a\"), \n  Option(\"b\"), \n  None\n).flatMap(\n  x => x\n)\n<\/pre>\n<p>If this isn&#8217;t want you want, you can also filter the list by whether the values are a None or not:<\/p>\n<pre lang=\"scala\">\nList(\n  Option(\"a\"), \n  Option(\"b\"), \n  None\n).filter(_.isDefined)\n\nres40: List[Option[String]] = \n  List(Some(a), Some(b))\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Different  a scala list that has Options in it<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[4],"tags":[480],"aioseo_notices":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/posts\/4332"}],"collection":[{"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/comments?post=4332"}],"version-history":[{"count":0,"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/posts\/4332\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/media?parent=4332"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/categories?post=4332"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.garysieling.com\/blog\/wp-json\/wp\/v2\/tags?post=4332"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}