Filter map for values of None Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!list comprehension vs. lambda + filterLarge-scale design in Haskell?Sorting the Map<Key,Value> in descending order based on the valueWhat's the idiomatic way to do a map/getOrElse returning Unit in Scala?map function for objects (instead of arrays)Filtering maps in iteratorFiltering json-map objects by fields value, which is Some(value)Scala - filter out null values in a Array[Map[String,Int]]How to transform a tuple element values in a list of two tuple using mapScala: map+filter instead of foldLeft

What are the main differences between the original Stargate SG-1 and the Final Cut edition?

Random body shuffle every night—can we still function?

How can a team of shapeshifters communicate?

One-one communication

Relating to the President and obstruction, were Mueller's conclusions preordained?

Rationale for describing kurtosis as "peakedness"?

As a dual citizen, my US passport will expire one day after traveling to the US. Will this work?

Why do early math courses focus on the cross sections of a cone and not on other 3D objects?

Putting class ranking in CV, but against dept guidelines

If Windows 7 doesn't support WSL, then what is "Subsystem for UNIX-based Applications"?

Delete free apps from library

A term for a woman complaining about things/begging in a cute/childish way

Is there public access to the Meteor Crater in Arizona?

Resize vertical bars (absolute-value symbols)

Trying to understand entropy as a novice in thermodynamics

Did pre-Columbian Americans know the spherical shape of the Earth?

Asymptotics question

Monty Hall Problem-Probability Paradox

Moving a wrapfig vertically to encroach partially on a subsection title

How many time has Arya actually used Needle?

Can you force honesty by using the Speak with Dead and Zone of Truth spells together?

In musical terms, what properties are varied by the human voice to produce different words / syllables?

Nose gear failure in single prop aircraft: belly landing or nose-gear up landing?

AppleTVs create a chatty alternate WiFi network



Filter map for values of None



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!list comprehension vs. lambda + filterLarge-scale design in Haskell?Sorting the Map<Key,Value> in descending order based on the valueWhat's the idiomatic way to do a map/getOrElse returning Unit in Scala?map function for objects (instead of arrays)Filtering maps in iteratorFiltering json-map objects by fields value, which is Some(value)Scala - filter out null values in a Array[Map[String,Int]]How to transform a tuple element values in a list of two tuple using mapScala: map+filter instead of foldLeft



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








33















I've searched around a bit, but haven't found a good answer yet on how to filter out any entries into a map that have a value of None. Say I have a map like this:



val map = Map[String, Option[Int]]("one" -> Some(1), 
"two" -> Some(2),
"three" -> None)


I'd like to end up returning a map with just the ("one", Some(1)) and ("two", Some(2)) pair. I understand that this is done with flatten when you have a list, but I'm not sure how to achieve the effect on a map without splitting it up into keys and values, and then trying to rejoin them.










share|improve this question




























    33















    I've searched around a bit, but haven't found a good answer yet on how to filter out any entries into a map that have a value of None. Say I have a map like this:



    val map = Map[String, Option[Int]]("one" -> Some(1), 
    "two" -> Some(2),
    "three" -> None)


    I'd like to end up returning a map with just the ("one", Some(1)) and ("two", Some(2)) pair. I understand that this is done with flatten when you have a list, but I'm not sure how to achieve the effect on a map without splitting it up into keys and values, and then trying to rejoin them.










    share|improve this question
























      33












      33








      33


      5






      I've searched around a bit, but haven't found a good answer yet on how to filter out any entries into a map that have a value of None. Say I have a map like this:



      val map = Map[String, Option[Int]]("one" -> Some(1), 
      "two" -> Some(2),
      "three" -> None)


      I'd like to end up returning a map with just the ("one", Some(1)) and ("two", Some(2)) pair. I understand that this is done with flatten when you have a list, but I'm not sure how to achieve the effect on a map without splitting it up into keys and values, and then trying to rejoin them.










      share|improve this question














      I've searched around a bit, but haven't found a good answer yet on how to filter out any entries into a map that have a value of None. Say I have a map like this:



      val map = Map[String, Option[Int]]("one" -> Some(1), 
      "two" -> Some(2),
      "three" -> None)


      I'd like to end up returning a map with just the ("one", Some(1)) and ("two", Some(2)) pair. I understand that this is done with flatten when you have a list, but I'm not sure how to achieve the effect on a map without splitting it up into keys and values, and then trying to rejoin them.







      scala functional-programming hashmap filtering






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Aug 7 '12 at 21:30









      KChalouxKChaloux

      2,22832640




      2,22832640






















          3 Answers
          3






          active

          oldest

          votes


















          35














          Like every collection type in the scala.collection namespace a Map has the filter method defined and Optionhas the isDefined method, which is true for Some and false for None. You can filter out the Nonevalues by combining these two:



          scala> map.filter(_._2.isDefined)
          res4: scala.collection.immutable.Map[String,Option[Int]] = Map(one -> Some(1), two -> Some(2))





          share|improve this answer























          • Neato. I wouldn't have guessed the syntax though. Still a little confused on _. From what I understand, we're telling it to go to the second item (the value) of the first (current) pair?

            – KChaloux
            Aug 7 '12 at 21:47






          • 2





            @KChaloux In this case _ refers to the first argument of a function literal being passed to the filter method. It's a shorthand for x => x._2.isDefined

            – Nikita Volkov
            Aug 7 '12 at 22:13











          • And the _2 comes from the Tuple.

            – fracz
            Nov 1 '15 at 19:48


















          46














          If you're filtering out None values, you might as well extract the Some values at the same time to end up with a Map[String,Int]:



          scala> map.collect case (key, Some(value)) => (key, value) 
          res0: scala.collection.immutable.Map[String,Int] = Map(one -> 1, two -> 2)





          share|improve this answer
































            6














            Also
            map.filterKeys( map(_) != None)



            or



            for( (k,v) <- map if( v!= None)) yield (k,v)



            This approach provides a general filterValues method that doesn't exist on maps.

            I miss such a method, because none of the alternatives is perfect.



            [Updated later] This is a better version that doesn't do a lookup on each entry and still reads reasonably clearly.



            map.filter( case (x,y)=> y!=None)






            share|improve this answer

























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f11854433%2ffilter-map-for-values-of-none%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              35














              Like every collection type in the scala.collection namespace a Map has the filter method defined and Optionhas the isDefined method, which is true for Some and false for None. You can filter out the Nonevalues by combining these two:



              scala> map.filter(_._2.isDefined)
              res4: scala.collection.immutable.Map[String,Option[Int]] = Map(one -> Some(1), two -> Some(2))





              share|improve this answer























              • Neato. I wouldn't have guessed the syntax though. Still a little confused on _. From what I understand, we're telling it to go to the second item (the value) of the first (current) pair?

                – KChaloux
                Aug 7 '12 at 21:47






              • 2





                @KChaloux In this case _ refers to the first argument of a function literal being passed to the filter method. It's a shorthand for x => x._2.isDefined

                – Nikita Volkov
                Aug 7 '12 at 22:13











              • And the _2 comes from the Tuple.

                – fracz
                Nov 1 '15 at 19:48















              35














              Like every collection type in the scala.collection namespace a Map has the filter method defined and Optionhas the isDefined method, which is true for Some and false for None. You can filter out the Nonevalues by combining these two:



              scala> map.filter(_._2.isDefined)
              res4: scala.collection.immutable.Map[String,Option[Int]] = Map(one -> Some(1), two -> Some(2))





              share|improve this answer























              • Neato. I wouldn't have guessed the syntax though. Still a little confused on _. From what I understand, we're telling it to go to the second item (the value) of the first (current) pair?

                – KChaloux
                Aug 7 '12 at 21:47






              • 2





                @KChaloux In this case _ refers to the first argument of a function literal being passed to the filter method. It's a shorthand for x => x._2.isDefined

                – Nikita Volkov
                Aug 7 '12 at 22:13











              • And the _2 comes from the Tuple.

                – fracz
                Nov 1 '15 at 19:48













              35












              35








              35







              Like every collection type in the scala.collection namespace a Map has the filter method defined and Optionhas the isDefined method, which is true for Some and false for None. You can filter out the Nonevalues by combining these two:



              scala> map.filter(_._2.isDefined)
              res4: scala.collection.immutable.Map[String,Option[Int]] = Map(one -> Some(1), two -> Some(2))





              share|improve this answer













              Like every collection type in the scala.collection namespace a Map has the filter method defined and Optionhas the isDefined method, which is true for Some and false for None. You can filter out the Nonevalues by combining these two:



              scala> map.filter(_._2.isDefined)
              res4: scala.collection.immutable.Map[String,Option[Int]] = Map(one -> Some(1), two -> Some(2))






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Aug 7 '12 at 21:34









              drexindrexin

              21.9k35876




              21.9k35876












              • Neato. I wouldn't have guessed the syntax though. Still a little confused on _. From what I understand, we're telling it to go to the second item (the value) of the first (current) pair?

                – KChaloux
                Aug 7 '12 at 21:47






              • 2





                @KChaloux In this case _ refers to the first argument of a function literal being passed to the filter method. It's a shorthand for x => x._2.isDefined

                – Nikita Volkov
                Aug 7 '12 at 22:13











              • And the _2 comes from the Tuple.

                – fracz
                Nov 1 '15 at 19:48

















              • Neato. I wouldn't have guessed the syntax though. Still a little confused on _. From what I understand, we're telling it to go to the second item (the value) of the first (current) pair?

                – KChaloux
                Aug 7 '12 at 21:47






              • 2





                @KChaloux In this case _ refers to the first argument of a function literal being passed to the filter method. It's a shorthand for x => x._2.isDefined

                – Nikita Volkov
                Aug 7 '12 at 22:13











              • And the _2 comes from the Tuple.

                – fracz
                Nov 1 '15 at 19:48
















              Neato. I wouldn't have guessed the syntax though. Still a little confused on _. From what I understand, we're telling it to go to the second item (the value) of the first (current) pair?

              – KChaloux
              Aug 7 '12 at 21:47





              Neato. I wouldn't have guessed the syntax though. Still a little confused on _. From what I understand, we're telling it to go to the second item (the value) of the first (current) pair?

              – KChaloux
              Aug 7 '12 at 21:47




              2




              2





              @KChaloux In this case _ refers to the first argument of a function literal being passed to the filter method. It's a shorthand for x => x._2.isDefined

              – Nikita Volkov
              Aug 7 '12 at 22:13





              @KChaloux In this case _ refers to the first argument of a function literal being passed to the filter method. It's a shorthand for x => x._2.isDefined

              – Nikita Volkov
              Aug 7 '12 at 22:13













              And the _2 comes from the Tuple.

              – fracz
              Nov 1 '15 at 19:48





              And the _2 comes from the Tuple.

              – fracz
              Nov 1 '15 at 19:48













              46














              If you're filtering out None values, you might as well extract the Some values at the same time to end up with a Map[String,Int]:



              scala> map.collect case (key, Some(value)) => (key, value) 
              res0: scala.collection.immutable.Map[String,Int] = Map(one -> 1, two -> 2)





              share|improve this answer





























                46














                If you're filtering out None values, you might as well extract the Some values at the same time to end up with a Map[String,Int]:



                scala> map.collect case (key, Some(value)) => (key, value) 
                res0: scala.collection.immutable.Map[String,Int] = Map(one -> 1, two -> 2)





                share|improve this answer



























                  46












                  46








                  46







                  If you're filtering out None values, you might as well extract the Some values at the same time to end up with a Map[String,Int]:



                  scala> map.collect case (key, Some(value)) => (key, value) 
                  res0: scala.collection.immutable.Map[String,Int] = Map(one -> 1, two -> 2)





                  share|improve this answer















                  If you're filtering out None values, you might as well extract the Some values at the same time to end up with a Map[String,Int]:



                  scala> map.collect case (key, Some(value)) => (key, value) 
                  res0: scala.collection.immutable.Map[String,Int] = Map(one -> 1, two -> 2)






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Oct 29 '15 at 15:31









                  Zoltán

                  14k867112




                  14k867112










                  answered Aug 7 '12 at 23:01









                  Kristian DomagalaKristian Domagala

                  3,1701521




                  3,1701521





















                      6














                      Also
                      map.filterKeys( map(_) != None)



                      or



                      for( (k,v) <- map if( v!= None)) yield (k,v)



                      This approach provides a general filterValues method that doesn't exist on maps.

                      I miss such a method, because none of the alternatives is perfect.



                      [Updated later] This is a better version that doesn't do a lookup on each entry and still reads reasonably clearly.



                      map.filter( case (x,y)=> y!=None)






                      share|improve this answer





























                        6














                        Also
                        map.filterKeys( map(_) != None)



                        or



                        for( (k,v) <- map if( v!= None)) yield (k,v)



                        This approach provides a general filterValues method that doesn't exist on maps.

                        I miss such a method, because none of the alternatives is perfect.



                        [Updated later] This is a better version that doesn't do a lookup on each entry and still reads reasonably clearly.



                        map.filter( case (x,y)=> y!=None)






                        share|improve this answer



























                          6












                          6








                          6







                          Also
                          map.filterKeys( map(_) != None)



                          or



                          for( (k,v) <- map if( v!= None)) yield (k,v)



                          This approach provides a general filterValues method that doesn't exist on maps.

                          I miss such a method, because none of the alternatives is perfect.



                          [Updated later] This is a better version that doesn't do a lookup on each entry and still reads reasonably clearly.



                          map.filter( case (x,y)=> y!=None)






                          share|improve this answer















                          Also
                          map.filterKeys( map(_) != None)



                          or



                          for( (k,v) <- map if( v!= None)) yield (k,v)



                          This approach provides a general filterValues method that doesn't exist on maps.

                          I miss such a method, because none of the alternatives is perfect.



                          [Updated later] This is a better version that doesn't do a lookup on each entry and still reads reasonably clearly.



                          map.filter( case (x,y)=> y!=None)







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Aug 16 '16 at 17:21

























                          answered Nov 19 '13 at 20:05









                          ConorRConorR

                          33237




                          33237



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f11854433%2ffilter-map-for-values-of-none%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                              Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                              Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved